AGENTS.md instructions for /Users/pfleidi/entire/cli/.worktrees/checkpoint-policy-command
Simplicity, maintainability, and clarity are primary goals. Optimize for them over cleverness, line count, perceived completeness, or short-term convenience. These values inform every section below; when this section and another appear to conflict, choose the option that better serves these values.
Simplicity: the smallest design that solves the current problem, measured by total conceptual load — not just diff size. A small local change that adds a new mode, concept, or exception developers must track is worse than a larger change that keeps the model coherent. Fewer files, fewer abstractions, fewer moving parts. Add structure only when the task forces it, not for hypothetical future needs.
Maintainability: code the next reader (often future-you) can change confidently. Prefer obvious flow, explicit dependencies, and patterns consistent with the surrounding code over local optimizations that hide intent.
Clarity: names, types, and structure should explain themselves. When code isn't clear, rewrite it; don't annotate it.
Comments default to zero. Code explains what via names and structure; comments add why, and only when the why is non-obvious. Comments must describe the code that is — never code that was, code that might be, or process around the code. Most code needs no comments at all. Comments that restate, paraphrase, narrate, header, or summarize the code rot when code changes and generate false-positive review-bot flags.
OK to write, when concise and actively helpful:
Public function/method docs: a brief description of exported symbols when the signature and name don't already convey the contract. One or two sentences max, oriented to the caller; no implementation narration.
Module/package docs: a top-of-file or top-of-module summary, with a short usage example when it materially helps a new reader. Skip if the package name and exported surface already explain themselves.
Non-obvious "why" inline: hidden constraint, workaround for a specific bug, surprising behavior. One line where possible.
Test-chunk summary: a single concise line summarizing what a multi-line chunk of test setup or action accomplishes (e.g., // Point v1 at the new commit, then snapshot it.). If a chunk needs more, extract a named helper.
Issue-URL pointer: a single-line link to an issue or stable doc that explains why current code is shaped this way (e.g., // Workaround for upstream bug: https://github.com/foo/bar/issues/123).
Never write:
Doc blocks for non-public symbols, or doc blocks for public symbols that simply restate the name and signature.
Inline narration of control flow (// loop over users, // check if valid).
Commentary referencing the change that introduced the line (// added for X, // fixed bug Y, // new in Q3).
TODO, FIXME, HACK, XXX, or any other deferred-work marker. Unfinished work belongs in issue tracking; if it's worth remembering, file an issue rather than commenting in code.
Future plans, intended refactors, or speculative roadmaps (// will switch to gRPC in Q4, // migrate to X once Y lands).
Any comment that would still be true if the next line of code were deleted.
Before writing any comment, ask whether a competent reader given only the code would miss something important. If no, write nothing.
Apply across planning, implementation, refactors, reviews, commits, and PR descriptions. If a change adds complexity, state the case for it explicitly. When uncertain, pick the option that is easier to read, easier to delete, and easier to revisit in six months.
Workflow
Plan First
For new features, refactors, multi-file changes, or architecture-affecting work:
Enter plan mode. Read relevant source, trace execution paths, write a step-by-step implementation plan, then wait for approval before editing.
The plan declares two things at the top: an execution mode (step-by-step (default) or one-shot, with a rationale that names the factors weighed) and a commit shape — the series of small focused commits the work will land as, with one-line subjects. User can override either at plan approval.
After approval, execute per the declared mode. A behavior-changing unit includes code and directly related tests together; do not split implementation and tests across checkpoints.
Pause for review at every checkpoint — after each step in step-by-step mode, once at the end in one-shot mode. Call out key decisions or surprises not obvious from the diff; skip narrating what the diff already shows.
Choosing the mode. Judge whether the resulting diff is small enough to review in one pass. Weigh:
Net new or modified production code (lines and files)
New concepts, abstractions, exceptions, modes, or vocabulary introduced
Breadth of impact — does the change stay contained or ripple through callers?
Whether the change extends established patterns or introduces new ones
Pure deletions (files, functions, tests) and new tests weigh lightly — they are easy to scan on their own. New or modified production code weighs heavily, especially anything that adds a concept developers will need to remember (see Values). When uncertain, choose step-by-step. State the factors weighed in the plan's rationale so the user can sanity-check.
Step-by-step is always required, regardless of size, when the change touches: shared interfaces, public APIs, exported types, dependencies, schemas (DB/config/IPC), destructive operations, or any product/design choice that can't be inferred from the request.
If during one-shot execution the change grows past what was estimated, pause, present what's done, and ask whether to continue one-shot or split into steps.
Committing is mode-specific. In step-by-step mode, each checkpoint is a commit point: wait for explicit approval, then stage and commit that step before moving on. In one-shot mode, no commits happen during execution; at the final checkpoint the user reviews the full working-tree diff locally, and on approval the agent stages and commits the planned commit shape in order (by path, or git add -p for hunk splits). Never commit without explicit approval. If the work diverged from the planned commit shape, propose a revised shape and wait for approval before committing.
A checkpoint means "this batch is reviewable now", not "finish everything." No form of agreement, enthusiasm, or repeated approval is permission to skip the next checkpoint unless the user explicitly says so. Silence never means continue. Plans must not defer tests to a final phase when in-step tests are possible. Prefer TDD, but complete the focused red-to-green cycle before each checkpoint: write/update the failing test, run it to confirm failure, implement the solution, rerun the focused test to confirm it passes, then stop. Do not stop after only adding the failing test unless the user explicitly asks. If TDD is not practical, add/update directly related tests immediately after the code change, before the checkpoint.
Brief affirmatives ("continue", "next", "go", "proceed", "ok", or similar) after a checkpoint count as approval for the next batch — one step in step-by-step mode, the remainder if a one-shot run was paused for scope growth, or the planned commit-shape batch at the final one-shot checkpoint. Within an approved investigation or plan, do not pause for permission before running read-only commands (grep, file reads, status, log) that fall in the agreed scope; announce briefly if useful and proceed.
Execute Directly
For skill workflows (pfleidi:review, pfleidi:pr-feedback, pfleidi:pr, pfleidi:clean-go, etc.) or small targeted changes, follow the skill directly without extra plan mode. For small non-skill changes, read the relevant code, make the change, and present the result.
Low-Input Skill Defaults
For pfleidi:* skills, prefer safe progress over repeated prompts. Use the skill's default path without asking for mode selection, and continue through independent items when one item is blocked. Ask only before commits, pushes that are not already part of the invoked skill, destructive actions, force-pushes, new dependencies, shared/public interface changes, unrelated-file changes, or product/design choices that cannot be inferred from the user's request, implementation plan, PR description, or source.
When an individual finding or review comment is ambiguous, skip that item, continue with the remaining unambiguous items, and list the skipped item with the exact decision needed at the end. Do not let one unclear item block unrelated mechanical or high-confidence fixes.
Testing Strategy
Tests should verify meaningful behavior at the smallest scope that gives real confidence without distorting production code. Prefer contract/user-visible behavior over implementation details, and do not chase line coverage with brittle tests.
Use unit tests for pure logic, small components, parsing/validation, and behavior with explicit dependencies that can be supplied naturally.
Use integration tests when behavior depends on real wiring, filesystem, config, databases, process boundaries, generated code, or framework behavior, or when a unit test would require awkward mocks or production-only seams.
Use end-to-end or smoke tests for critical flows across the full system. Keep them few, stable, and high value.
Cover changed behavior, important edge cases, and error paths. If a changed path is not tested, state why it is untestable or low risk.
When tests require broad mocks, mutable globals, function-variable seams, or test-only production hooks, reconsider the dependency design or raise the test scope.
Use pfleidi:testing for detailed local guidance on test scope, test seams, mocks, and test helper abstraction.
Reviews should flag both missing tests and tests written at the wrong abstraction level.
Always
Never commit without explicit user approval.
Keep behavior changes and their tests commit-ready in the same logical step/diff. If no test is added, the user must have asked for no tests or the change must be truly untestable; state why.
Code reviews compare only against origin/main; do not use local main, merge-base shortcuts, PR bases, or alternate bases.
For exploration/analysis, read actual source files. Subagents are for bounded parallel research that returns a summary, keeping raw output out of the main context — not for replacing source reading on decisions. When a skill explicitly uses subagents, launch them as directed. Verify any subagent findings against source before acting.
Communication
If user-facing prose uses CS-cliche terms like invariant, idempotent, canonical, orthogonal, or monotonic, briefly undercut yourself with a small self-deprecating aside about being a computer science cliche. Keep it light and infrequent. Do not put jokes in code, tests, commit messages, PR titles, or technical artifacts unless asked.
Use honestly sparingly. Avoid it as filler or a default sentence opener; only use it when the word changes the meaning.
When the next action is unambiguous from the approved plan or the user's instruction, take the action. Skip preludes like "let me think about this" or "I'll start by reading X" unless the choice is genuinely non-obvious.
When the user asks for a handover doc, summary, writeup, status note, or other prose they are likely to share with another agent or coworker, present the text first, then offer to copy it to the clipboard via pbcopy. If accepted, pipe the exact same text through pbcopy using a heredoc to preserve formatting, and confirm in one short line. Skip the offer for short inline answers, code being applied directly to files, or tool output only useful within the current thread.
Document References
Do not use opaque identifiers like §5.2, paragraph numbers, list item numbers, or generated IDs as the main way to refer to document content in user-facing prose.
When a source document has numbered sections, paragraph numbers, clauses, exhibits, or list items, pair the source identifier with a human-readable label on first mention, such as termination notice requirement (§5.2) or payment timing clause (item 3).
After first mention, refer to the descriptive label, not just the number. Humans should not need to remember what §5.2 meant earlier.
If the source item has no useful heading, create a short factual label from its content. Keep the original number in parentheses only when it helps trace the reference back to the source.
In tables, review notes, summaries, and change lists, prefer meaningful identifiers like Payment timing, Renewal notice, or Data retention exception over bare numeric labels.
Search
Use ripgrep (rg) before slower tools like grep. Bound result size: prefer rg -l (filenames) or rg -c (counts) to locate first, then read only the matched files or sections. Restrict paths when the area is known.
Code Navigation
Use rg for broad text/file discovery. When language-server or semantic code tools are available, prefer them for Go symbol-level questions such as definitions, references, call sites, renames, diagnostics, and package-aware navigation. Do not replace fast text search with semantic tools for simple string/config/doc searches. Treat language-server results as navigation help, not proof; verify behavior by reading source and running focused tests.
When a workspace file's relevant range is already known, read it in a slice (offset/limit) using the file-read tool rather than re-reading the whole file.
Scope Control
Diffs should stay scoped to the task. Every changed file/line must directly support it.
YAGNI is the default. The best code is often code that is simplified, removed, or never written.
Treat lines of code and new concepts as costs. Prefer the least complex change that fully satisfies the task, including necessary tests and verification.
Before adding code, check whether the task can be solved by deleting code, reusing an existing path, tightening existing logic, or narrowing scope.
Do not add speculative hooks, options, interfaces, helper layers, configuration, generalization, or "future-proofing" unless the current task requires them.
When planning or explaining a change, call out the simpler alternatives considered and why the chosen approach is the smallest correct one.
If a fix is becoming additive or sprawling, pause and re-evaluate whether the problem has been framed at the right level before continuing.
No unrelated refactors, wrapper structs, abstractions, renames, reorganization, "improvements", cleanup, formatting, dependency updates, generated files, or config changes unless required.
Do not introduce production code that exists only to make tests easier, such as mutable function variables used as test seams, mutable package-wide settings, test-only hooks, or exported reset helpers. Treat this as a design smell: prefer real dependency injection through existing construction paths, typed interfaces around external effects, or a higher-scope test such as an integration test when unit isolation would require distorting production code.
List improvement opportunities separately; never bundle them into the change.
Before presenting work, committing, or opening a PR, review changed files. Remove your own unrelated changes; call out unrelated user changes separately.
Address all in-scope items, not just the first. Confirm full scope before starting when multiple items need attention.
Before fixing a bug, decide whether it is local or systemic. Fix at the narrowest correct level: local one-offs in place, systemic issues at the shared source/pattern plus directly related in-scope occurrences. Do not add caller-side patches that merely hide a systemic bug.
Keep functions/methods at one level of abstraction. High-level functions should orchestrate meaningful helpers instead of embedding low-level details; low-level helpers should stay focused on low-level work and call similarly low-level helpers.
Stop and ask before adding dependencies, changing shared interface signatures, or modifying code outside files directly related to the task.
Changelogs
Do not edit changelogs during ordinary development unless the user explicitly asks for a changelog update. Changelog entries are release work, not part of routine feature, bugfix, or refactor changes.
Do not retroactively edit historical changelog entries. Existing dated or versioned entries are release history, not a live inventory of current behavior. Only edit older changelog entries when the user explicitly asks for that exact historical correction.
Changelog edits are appropriate for explicit release-prep/versioning tasks, explicit user-requested changelog updates, or narrow typo, broken-link, or formatting fixes that do not change the recorded meaning of a past release.
Go Development
For larger Go edits, refactors, or Go reviews, use pfleidi:clean-go.
After Go edits, run focused verification that covers the changed packages: format edited files with gofmt/goimports when relevant, run a relevant build/vet command, run the project's lint task, and run focused tests. Use full ./... only when changes affect shared APIs, package boundaries, generated code, or broad behavior. Prefer lint-specific tasks such as make lint, mise run lint, or CI/README-documented lint commands. Do not use aggregate check, ci, or verify tasks as lint unless confirmed lint-only. Run golangci-lint run ./... only if documented or no project lint task exists and the binary is available.
Go style preferences: keep new declarations readable top-to-bottom without reordering existing code just for style; prefer composable functions with meaningful intermediate values over pass-through helper chains; avoid ambiguous (result, bool) returns except clear ok/found/exists presence signals. For deeper Go cleanliness guidance, use pfleidi:clean-go.
Verification
Do not run formatters, linters, builds, or tests after every small edit. Run verification at natural boundaries: after a complete logical step when behavior changed, after refactors that touch production code, before presenting final work when risk is non-trivial, before committing when explicitly asked to commit, and before opening a PR via the PR skill. Prefer focused checks over full-suite checks. A pre-commit hook or make precommit/mise run precommit may be used as the final commit safety net, but it must stay fast and scoped to staged or directly affected files/packages.
After refactors or production-code changes, include a relevant compile/build check in boundary verification when the project has one. Do not present the work as done, reviewable, or commit-ready while the compile/build status is failing or unknown. If a compile/build command fails because of in-scope changes, fix those failures before asking the user to commit. If the failure is unrelated, too broad, or no relevant compile/build command is discoverable, say so explicitly and do not describe the work as commit-ready; leave the commit decision with the user.
Reuse prior results within the session. If a focused check (test, build, lint) passed earlier and nothing it depends on has changed since — production or test files in its scope — do not re-run it. Note "still valid from <prior step/run>" and skip.
When running linters, tests, or builds, show evidence: command, exit status, and relevant output. For short outputs or failures, show complete output. For long successful outputs, show the relevant excerpt and state that the rest was truncated. Never summarize as "passing" or "clean" without command evidence. If a command fails, report it immediately; do not silently retry or omit it. Before claiming how code works, verify by reading source.
Minimize output at the command level, not just in the displayed transcript. Prefer flags that narrow output: git diff --stat before full git diff, git diff -- <path> once the path is known, go test -run TestName -count=1 ./pkg/... instead of full-suite runs, -v only when debugging a specific failure, and scoped lint targets over full-repo lint. Quieter commands still produce the evidence required above; verbose commands waste context.
Token Discipline
Reuse prior output. If a command's result is already in the conversation and the underlying state has not changed, do not re-run it.
When a search returns more than ~50 hits or a candidate file exceeds ~500 lines, summarize the shape of the results and ask which subset matters before reading further.
If the conversation has accumulated heavy investigation output, suggest starting a fresh thread before moving into implementation; carrying long context costs more per turn and degrades focus.
When a routine read-only command repeatedly triggers an approval prompt, offer to add it to the allowlist (via the fewer-permission-prompts skill) rather than continuing to ask each time.
Prefer single commands over shell pipelines. Piped read-only probes like git show HEAD:path | sed -n '10,40p' split into multiple permission checks and can block background review agents. Use tool-native range reads for workspace files, path-scoped commands such as git diff <base> -- <path>, or one standalone command whose output is acceptable. If a script grows past a few lines, write it to the project-local artifact directory when available; otherwise ask before creating a script in /tmp.
Never wrap validation commands in sh -c, shell redirection, tee, command separators, or pipelines solely to capture logs. Run the exact build/lint/test command directly so prefix approvals such as mise run or go test can apply. If a log artifact is useful, copy the command output after it completes when that is possible without rerunning through a shell wrapper; otherwise show the captured output and mark the file log as unavailable.
For long-running commands (builds, full test runs, watchers, streaming logs), use the Bash tool's run_in_background parameter rather than blocking the turn; check progress on demand instead of holding the output stream open.
For temporary documents, logs, ledgers, and caches, use project-local ./tmp/<agent-name>/<doc-name> only when ./tmp/ already exists and is already ignored. If no project-local artifact directory is available, do not create file artifacts by default; keep the information in the response or mark the artifact path n/a. Ask before using /tmp/<agent-name>/<doc-name> or modifying ignore files.
When a single investigation produces findings worth re-citing across turns, offer to persist them to a local notes file in the artifact directory and reference the file on later turns rather than re-reading scrollback.
Multi-Terminal Awareness
When rerunning commands or revisiting work, re-read current state from scratch — but only the surfaces about to be acted on (changed files, current branch, the specific path in question). Assume other terminals may have changed the branch. Do not re-survey the whole repo on every turn.
Git Workflow
Commit-Time Verification
Before committing, run only a quick sanity check:
review changed files/diff for intended contents
run a relevant compile/build command for code changes when one is discoverable
run the project lint task, scoped when supported
run only tests directly related to changed code
Do not run full suites before routine commits unless asked. Avoid commit-time defaults like mise run check, mise check, make check, make ci, make verify, full-repo go test ./..., or full project tests. If only a slow aggregate command exists, say so and ask before running it. If code changed and no relevant compile/build command can be found or run, do not create an agent-authored commit; report the gap and ask the user how to proceed.
Git Operations
Combine git add and git commit in one shell command, e.g. git add file1 file2 && git commit -m "subject" -m "body".
Revert surgically (git checkout main -- <file>, git revert); never hard-reset whole branches.
Never force push without consent. Avoid amending; if amendment is needed, first check whether the commit was pushed. If pushed, create a new commit instead.
Commit Messages
Write messages from the actual diff (git diff / git diff --cached) and describe only the net change since the previous commit. Do not describe process, debugging, conversation, undone work, or intermediate states. Write as if the code was produced in one pass.
Default to common Git commit structure:
Subject: concise imperative summary, ideally 50 characters or fewer, no trailing period.
Blank line after the subject.
Body: a few short lines of context explaining why the change was made and any important constraints, wrapped around 72 characters. Prefer this body for anything non-trivial; omit it only for truly obvious mechanical changes.
When committing non-interactively, use multiple -m flags so the subject and body are separated cleanly, for example:
bash
git add file1 file2 && git commit -m "fix config validation" -m "Reject empty config paths before loading files.
This keeps the error close to the caller and avoids silently falling back to defaults."
Never add Co-Authored-By:.
Worktrees
Worktrees are user-managed only. Never run git worktree *; never rm, mv, or otherwise modify .worktrees/ or any path returned by git worktree list. If a skill, workflow, or doc asks for worktree cleanup or other worktree operations, stop and report what it wanted to do. Do not ask permission to run it.
The only exception is pfleidi:pr-review, which may use the existing .worktrees/review checkout to check out and fast-forward a PR branch for local review. It still must not create, delete, clean, reset, or otherwise manage worktrees.
Commit and Continue
"Commit and continue" (and variants) is an explicit synonym for approving a step-by-step checkpoint: commit only the current uncommitted changes (no amend, no push), then start the next step. "Continue" means the next step, not all remaining steps.
Pull Requests
Write concise PR descriptions: problem solved and how. No self-promotion or "Generated with Claude Code" references.
For PRs that are mostly Markdown changes, include links to the rendered Markdown files on GitHub.
For PR scope/title/body checks, compare branch-only changes from the merge base with remote origin/main; never use local main or direct git diff main / git diff origin/main output that includes upstream-only changes.
Before creating a PR, verify every changed file belongs to the PR goal. If unrelated files/commits exist, stop and ask whether to split/remove them.
Deduplicate PR verification by coverage area. Do not run both aggregate tasks and subtasks, duplicate lint/build/test coverage from multiple sources, or every CI matrix shard locally when a local unsharded/representative task covers the suite. If full CI-only shard/e2e coverage is the only option, ask before running it.
Plans
Never check in plan files unless explicitly asked.
--- 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 five noun groups plus a small set of
top-level verbs. The groups are the canonical home for each verb; legacy
top-level shortcuts remain functional but hidden, and emit a deprecation hint
pointing at the canonical group form. Newer experimental command families are
discoverable through entire labs and may remain hidden from root help while
their canonical paths are still runnable.
session (alias: sessions): list, info, tokens, stop, attach, 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).
checkpoint (aliases: cp, checkpoints): list, explain, tokens, search, plus
the deprecated rewind (functional, prints a cobra deprecation message, will
be removed in a future release)
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. 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
Experimental command families advertised through entire labs:
tokens: profile (hidden from root help while token diagnostics mature)
Hidden top-level shortcuts (functional, emit a one-line deprecation hint):
resume → session resume, attach → session attach, explain →
checkpoint explain, trace → doctor trace.
Cobra-native aliases (no hint): sessions → session, cp/checkpoints →
checkpoint. The search top-level remains hidden without a hint.
Deprecated top-level commands (functional, print a cobra deprecation message):
reset → clean, and rewind (no replacement, announces removal — same
deprecation as checkpoint rewind).
The hideAsAlias(cmd, canonical) helper in cmd/entire/cli/aliascmd.go
marks a command Hidden and sets cobra's Deprecated field so the hint
renders to stderr on every invocation while the command stays functional.
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.
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:
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.
Control-Plane Core Resolution (which core am I talking to?)
Control-plane commands dial one of three cores: the active context's
(coreapi.New), a specific cluster's (coreapi.NewForCluster), or — when
ENTIRE_TOKEN is set — the env token's aud (the bypass inside New/
NewForCluster). This precedence lives only inside coreapi; nothing else
re-derives it.
To display which core a request uses, ask the client: client.CoreOrigin().
It returns whatever was actually wired in, so the shown core can never diverge
from where the request goes. Do NOT re-resolve with
auth.ResolveControlPlaneTarget() for display — it only knows the active
context and silently ignores both ENTIRE_TOKEN and the cluster case, so it can
name a core the request never touches (this was a real bug in the mirror list
banner; see repo_mirror.go and coreapi.Client.CoreOrigin).
When a command resolves auth outside a coreapi.Client (e.g. entire auth status, which builds its own /me client), it must apply the same
env-token-first precedence itself — see resolveAuthStatusTarget /
resolveEnvTokenStatusTarget in auth.go, which branch on
auth.EnvTokenVar before falling back to the active context. logout is the
deliberate exception: it manages a stored login session, which an ephemeral
env token has none of, so it stays on the active context.
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
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
Each committed session stores the raw transcript (full.jsonl, read by CLI rewind/resume/explain) plus a best-effort compact transcript (transcript.jsonl, generated via transcript/compact and pre-sliced to the checkpoint's checkpoint_transcript_start). Both are pushed with the v1 branch. The root metadata.jsonsessions[].transcript pointer keeps targeting full.jsonl; when the compact transcript was generated the session entry also carries a compact_transcript path pointing at transcript.jsonl (omitted otherwise) so external readers can locate it next to full.jsonl.
Uses the post-rewrite Git hook to keep local session linkage aligned after amend/rebase rewrites
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.
Token usage scoping - SessionState.TokenUsage is the session-wide total used by entire status; SessionState.CheckpointTokenUsage is the pending checkpoint delta since the last condensation. Checkpoint metadata must stay scoped to CheckpointTranscriptStart or the pending checkpoint delta. Cursor tokens come only from stop-hook payloads, while Copilot CLI can also backfill full-session totals from session.shutdown.
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
manual_commit_opf_rewrite.go - Pre-push OPF re-redaction: walks unpushed v1 commits, runs OPF over their blobs, rebuilds commits with Entire-OPF-Applied: true trailer, CAS-updates the local ref. Sentinel error types (use errors.As): V1DivergedError, BootstrapTooLargeError, V1RefMovedError, OPFRuntimeFailedError.
cleanup.go - Cleanup discovery/deletion for shadow branches, session states, and checkpoint metadata
session_state.go - Package-level session state functions
hooks.go - Git hook installation
Note: checkpoint/configloader.go overrides go-git's default config loader with a symlink-following billy.Basic (osSymlinkFS) — go-git's default reads config via os.Root, which rejects absolute symlinks in any path component (e.g. a ~/.config managed by a dotfile tool), silently dropping global config so author identity fell back to "Unknown" and signing was skipped.
Deep-Dive Reference
The phase state machine, metadata directory layout, sharded checkpoint format, multi-session metadata, checkpoint ID linking, commit trailers, and concurrent-session / shadow-branch-migration behavior are documented in:
Sessions and Checkpoints - domain model, storage layout, checkpoint ID linking, commit trailers, package structure
Checkpoint Scenarios - phase state machine and worked condensation scenarios
When Modifying the Strategy
The strategy must implement the full Strategy interface
Test with mise run test - strategy tests are in *_test.go files
Keep this file and docs/architecture/sessions-and-checkpoints.md current when changing strategy behavior (AGENTS.md is a symlink to this file)
entire review Command
entire review runs a set of configured review skills inside an agent session. The review session is an immutable fact attached to a checkpoint — no verdict, no status tracking, no empty commits. On the next git commit, the review session is condensed into the checkpoint metadata alongside normal sessions, permanently recording that the code was reviewed and which skills were run.
Configured per-agent in .entire/settings.json (EntireSettings.Review); launchable agents (claude-code, codex, gemini-cli) receive ENTIRE_REVIEW_* env vars that the UserPromptSubmit hook reads to tag the session as Kind = "agent_review". Multi-agent runs use a TUI dashboard + opt-in cross-agent synthesis.
See Review Command for the full command surface, settings schema, env-var handshake, multi-agent UI, anti-features (do NOT recreate), and key-file map.
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
Load context from the latest committed entire checkpoint
Assistant
Using using-superpowers for the session-start requirement and using-entire because this is an Entire checkpoint context request.
Assistant
I’ll check the local Entire state first, then read the newest committed checkpoint transcript/summary non-interactively.
Assistant
Entire is enabled on checkpoint-policy-command-semver. I see one modified file already present, so I’ll only run read-only checkpoint/history commands.
Assistant
The newest local commit with an Entire-Checkpoint trailer is 1f1d021 with checkpoint 5b9a51224543; I’m going to read that checkpoint now.
Assistant
The checkpoint metadata loaded, but the JSON explain only includes the summary fields. I’m checking the current checkpoint explain command shape to see whether it exposes the compact/full transcript directly.
Assistant
checkpoint explain --full is the right path for the stored human-readable context. I’ll load that next and keep the output bounded to the relevant checkpoint.
Assistant
I have the latest committed checkpoint loaded. I’m doing a small source read of the touched files now so the checkpoint-backed intent is tied to the current code, not just the transcript.
Assistant
One more narrow read: I’m using the short explain view to capture the checkpoint’s own prompt/intent without the full transcript volume.
Assistant
Loaded the latest committed Entire checkpoint: 5b9a51224543 on checkpoint-policy-command-semver, from commit 1f1d021 (support semver checkpoint formats).
Checkpoint-backed context:
The branch implements Option 1 for checkpoint policy versions using golang.org/x/mod/semver, after feedback to avoid hand-rolled parsing.
CheckpointFormat now stores Family plus normalized SemVer Version.
ParseFormat accepts forms like branch-v1, branch-v1.2, branch-v1.2.3, and prereleases; rejects v0 and build metadata.
Compare keeps family ordering, then delegates version ordering to semver.Compare.
Read/write support remains exact after normalization; only branch-v1/branch-v1.0.0 is currently supported.
The checkpoint touched:
cmd/entire/cli/checkpointpolicy/format.go
cmd/entire/cli/checkpointpolicy/format_test.go
cmd/entire/cli/checkpointpolicy/update_test.go
Current worktree note: there is now one modified file, cmd/entire/cli/checkpointpolicy/remote.go, which is outside that checkpoint and I have not touched.
User
$pfleidi:review
User
You are the second-pass coverage sweep for a pfleidi:review.
Workspace: /Users/pfleidi/entire/cli/.worktrees/checkpoint-policy-command
Base ref: origin/main
Review the current working tree diff exactly as git diff origin/main, including committed, staged, and unstaged changes. Do not edit files.
Do NOT rely on first-pass agent findings; none are provided. Independently re-read changed files and surrounding code needed to understand each path.
Changed files (4):
cmd/entire/cli/checkpointpolicy/format.go
cmd/entire/cli/checkpointpolicy/format_test.go
cmd/entire/cli/checkpointpolicy/remote.go
cmd/entire/cli/checkpointpolicy/update_test.go
Review context:
User goal: Review this branch with pfleidi:review; latest committed checkpoint adds SemVer checkpoint policy parsing.
Implementation plan: Use golang.org/x/mod/semver; keep read/write support exact; add downgrade tests; preserve policy behavior.
PR context: no PR found for checkpoint-policy-command-semver.
Commits: 441c44e6d2 merge main, f1efc116f6 Extract adoptRemoteBaseline helper in policy Sync, 4303aa652e merge main, 1f1d021958 support semver checkpoint formats.
Changed surface: checkpointpolicy format parsing/comparison, remote sync helper extraction, related tests.
Go dead-code check: skipped, deadcode command not found.
Inferred behavior: Checkpoint policy versions now canonicalize through SemVer; downgrade checks catch minor/patch/prerelease ordering; remote sync adopts remote baseline via a helper.
Review philosophy:
It is OK to find nothing. Do not manufacture findings.
High confidence only: every finding must explain specifically what goes wrong if unfixed.
Do not flag tradeoffs with no clear winner.
Review against the stated intent, not old behavior alone.
Use permission-friendly reads: no pipelines, command separators, or subshells. Use rg, file reads, and path-scoped git diff.
Coverage task:
Re-read changed files and surrounding code needed for each changed path.
Trace changed behavior through callers, callees, tests, configuration, git remote/policy storage paths, and CLI entry points where relevant.
Search for related patterns, duplicated logic, and helpers that affect changed code.
Look across all lenses: security, correctness, tests, simplification, readability, performance, and Go cleanliness.
Deadcode command was unavailable; search manually for obvious unreachable additions.
Prioritize missed Required findings over optional improvements.
Return only high-confidence findings with concrete file:line evidence and a short explanation of the traced path. If none, say no findings.
User
You are Agent 5: Clean Go & Modern Go for a pfleidi:review.
Workspace: /Users/pfleidi/entire/cli/.worktrees/checkpoint-policy-command
Base ref: origin/main
Review the current working tree diff exactly as git diff origin/main, including committed, staged, and unstaged changes. Do not edit files.
Before reviewing, read and follow these local skill files:
User goal: Review this branch with pfleidi:review; latest committed checkpoint adds SemVer checkpoint policy parsing.
Implementation plan: Use golang.org/x/mod/semver; keep read/write support exact; add downgrade tests; preserve policy behavior.
PR context: no PR found for checkpoint-policy-command-semver.
Commits: 441c44e6d2 merge main, f1efc116f6 Extract adoptRemoteBaseline helper in policy Sync, 4303aa652e merge main, 1f1d021958 support semver checkpoint formats.
Changed surface: checkpointpolicy format parsing/comparison, remote sync helper extraction, related tests.
Go dead-code check: skipped, deadcode command not found.
Inferred behavior: Checkpoint policy versions now canonicalize through SemVer; downgrade checks catch minor/patch/prerelease ordering; remote sync adopts remote baseline via a helper.
Review philosophy:
It is OK to find nothing. Do not manufacture findings.
High confidence only: every finding must explain specifically what goes wrong if unfixed.
Do not flag tradeoffs with no clear winner.
Review against the stated intent, not old behavior alone.
Use permission-friendly reads: no pipelines, command separators, or subshells. Use rg, file reads, and path-scoped git diff.
Clean Go lens: changed Go code plus necessary surrounding source, tests, interfaces, and call sites. Apply clean-go and version-gated modern Go checks only when concrete. Detect go.mod target version. Return only confirmed findings with file:line evidence. If none, say no findings.
User
You are Agent 4: Readability & Go Idioms for a pfleidi:review.
Workspace: /Users/pfleidi/entire/cli/.worktrees/checkpoint-policy-command
Base ref: origin/main
Review the current working tree diff exactly as git diff origin/main, including committed, staged, and unstaged changes. Do not edit files.
Changed files (4):
cmd/entire/cli/checkpointpolicy/format.go
cmd/entire/cli/checkpointpolicy/format_test.go
cmd/entire/cli/checkpointpolicy/remote.go
cmd/entire/cli/checkpointpolicy/update_test.go
Review context:
User goal: Review this branch with pfleidi:review; latest committed checkpoint adds SemVer checkpoint policy parsing.
Implementation plan: Use golang.org/x/mod/semver; keep read/write support exact; add downgrade tests; preserve policy behavior.
PR context: no PR found for checkpoint-policy-command-semver.
Commits: 441c44e6d2 merge main, f1efc116f6 Extract adoptRemoteBaseline helper in policy Sync, 4303aa652e merge main, 1f1d021958 support semver checkpoint formats.
Changed surface: checkpointpolicy format parsing/comparison, remote sync helper extraction, related tests.
Go dead-code check: skipped, deadcode command not found.
Inferred behavior: Checkpoint policy versions now canonicalize through SemVer; downgrade checks catch minor/patch/prerelease ordering; remote sync adopts remote baseline via a helper.
Review philosophy:
It is OK to find nothing. Do not manufacture findings.
High confidence only: every finding must explain specifically what goes wrong if unfixed.
Do not flag tradeoffs with no clear winner.
Review against the stated intent, not old behavior alone.
Use permission-friendly reads: no pipelines, command separators, or subshells. Use rg, file reads, and path-scoped git diff.
Readability lens: factoring, mixed abstraction levels, generated-code smell, data-flow opacity, control-flow complexity, naming clarity, Go API readability, and error readability. Explain concrete maintenance cost. Prefer small local suggestions; discard formatting-only or taste-only comments. Return only confirmed findings with file:line evidence. If none, say no findings.
User
You are Agent 3: Simplification & Efficiency for a pfleidi:review.
Workspace: /Users/pfleidi/entire/cli/.worktrees/checkpoint-policy-command
Base ref: origin/main
Review the current working tree diff exactly as git diff origin/main, including committed, staged, and unstaged changes. Do not edit files.
Changed files (4):
cmd/entire/cli/checkpointpolicy/format.go
cmd/entire/cli/checkpointpolicy/format_test.go
cmd/entire/cli/checkpointpolicy/remote.go
cmd/entire/cli/checkpointpolicy/update_test.go
Review context:
User goal: Review this branch with pfleidi:review; latest committed checkpoint adds SemVer checkpoint policy parsing.
Implementation plan: Use golang.org/x/mod/semver; keep read/write support exact; add downgrade tests; preserve policy behavior.
PR context: no PR found for checkpoint-policy-command-semver.
Commits: 441c44e6d2 merge main, f1efc116f6 Extract adoptRemoteBaseline helper in policy Sync, 4303aa652e merge main, 1f1d021958 support semver checkpoint formats.
Changed surface: checkpointpolicy format parsing/comparison, remote sync helper extraction, related tests.
Go dead-code check: skipped, deadcode command not found.
Inferred behavior: Checkpoint policy versions now canonicalize through SemVer; downgrade checks catch minor/patch/prerelease ordering; remote sync adopts remote baseline via a helper.
Review philosophy:
It is OK to find nothing. Do not manufacture findings.
High confidence only: every finding must explain specifically what goes wrong if unfixed.
Do not flag tradeoffs with no clear winner.
Review against the stated intent, not old behavior alone.
Use permission-friendly reads: no pipelines, command separators, or subshells. Use rg, file reads, and path-scoped git diff.
Simplification lens: dead code, existing utilities, duplicated functionality, copy-paste with variation, unnecessary abstractions, redundant work, missed concurrency, hot-path bloat, unnecessary existence checks, and unnecessary comments. Deadcode was skipped because the command is unavailable, so manually verify any dead-code claim. Return only confirmed findings with file:line evidence. If none, say no findings.
User
You are Agent 2: Correctness & Quality for a pfleidi:review.
Workspace: /Users/pfleidi/entire/cli/.worktrees/checkpoint-policy-command
Base ref: origin/main
Review the current working tree diff exactly as git diff origin/main, including committed, staged, and unstaged changes. Do not edit files.
Changed files (4):
cmd/entire/cli/checkpointpolicy/format.go
cmd/entire/cli/checkpointpolicy/format_test.go
cmd/entire/cli/checkpointpolicy/remote.go
cmd/entire/cli/checkpointpolicy/update_test.go
Review context:
User goal: Review this branch with pfleidi:review; latest committed checkpoint adds SemVer checkpoint policy parsing.
Implementation plan: Use golang.org/x/mod/semver; keep read/write support exact; add downgrade tests; preserve policy behavior.
PR context: no PR found for checkpoint-policy-command-semver.
Commits: 441c44e6d2 merge main, f1efc116f6 Extract adoptRemoteBaseline helper in policy Sync, 4303aa652e merge main, 1f1d021958 support semver checkpoint formats.
Changed surface: checkpointpolicy format parsing/comparison, remote sync helper extraction, related tests.
Go dead-code check: skipped, deadcode command not found.
Inferred behavior: Checkpoint policy versions now canonicalize through SemVer; downgrade checks catch minor/patch/prerelease ordering; remote sync adopts remote baseline via a helper.
Review philosophy:
It is OK to find nothing. Do not manufacture findings.
High confidence only: every finding must explain specifically what goes wrong if unfixed.
Do not flag tradeoffs with no clear winner.
Review against the stated intent, not old behavior alone.
Use permission-friendly reads: no pipelines, command separators, or subshells. Use rg, file reads, and path-scoped git diff.
Correctness lens: logic errors, nil handling, missing error checks, concurrency edge cases, redundant state, production test seams, parameter sprawl, leaky abstractions, stringly typed code, meaningful test gaps/wrong test scope, and test helper over-abstraction. Verify claims by reading source and relevant call sites. Return only confirmed findings with file:line evidence. If none, say no findings.
User
You are Agent 1: Security & Adversarial for a pfleidi:review.
Workspace: /Users/pfleidi/entire/cli/.worktrees/checkpoint-policy-command
Base ref: origin/main
Review the current working tree diff exactly as git diff origin/main, including committed, staged, and unstaged changes. Do not edit files.
Changed files (4):
cmd/entire/cli/checkpointpolicy/format.go
cmd/entire/cli/checkpointpolicy/format_test.go
cmd/entire/cli/checkpointpolicy/remote.go
cmd/entire/cli/checkpointpolicy/update_test.go
Review context:
User goal: Review this branch with pfleidi:review; latest committed checkpoint adds SemVer checkpoint policy parsing.
Implementation plan: Use golang.org/x/mod/semver; keep read/write support exact; add downgrade tests; preserve policy behavior.
PR context: no PR found for checkpoint-policy-command-semver.
Commits: 441c44e6d2 merge main, f1efc116f6 Extract adoptRemoteBaseline helper in policy Sync, 4303aa652e merge main, 1f1d021958 support semver checkpoint formats.
Changed surface: checkpointpolicy format parsing/comparison, remote sync helper extraction, related tests.
Go dead-code check: skipped, deadcode command not found.
Inferred behavior: Checkpoint policy versions now canonicalize through SemVer; downgrade checks catch minor/patch/prerelease ordering; remote sync adopts remote baseline via a helper.
Review philosophy:
It is OK to find nothing. Do not manufacture findings.
High confidence only: every finding must explain specifically what goes wrong if unfixed.
Do not flag tradeoffs with no clear winner.
Review against the stated intent, not old behavior alone.
Use permission-friendly reads: no pipelines, command separators, or subshells. Use rg, file reads, and path-scoped git diff.
Security lens: review for injection, path traversal, TOCTOU/race conditions, unvalidated boundary input, auth/authz gaps, leaked secrets. For each candidate, read actual source and trace production reachability. Return only confirmed findings with file:line evidence. If none, say no findings.
User
Code Review
1. Determine Diff Against origin/main
Always review changes against origin/main directly. Do not use local main, git merge-base, a PR base branch, or a user-specified alternate base.
Get the CURRENT diff — never use cached results from earlier in the conversation. Include both committed and uncommitted changes (staged + unstaged):
bash
BASE=origin/main
git diff $BASE --stat
Note: git diff origin/main (not origin/main...HEAD) diffs origin/main against the working tree, capturing committed changes, staged changes, and unstaged changes in one pass.
Show the user the file list and total count. If there are 0 changed files, report that to the user and stop — there is nothing to review. Otherwise, immediately proceed to the review agents. Do NOT wait for confirmation.
When the repository is a Go project and the diff includes Go-related files (*.go, go.mod, or go.sum), run a read-only dead-code check before launching agents:
bash
deadcode -test ./...
Use the output as review input only. If the output is broad, rerun with -filter scoped to packages touched by the diff. Do not install deadcode, run go install, or download tooling as part of the review. If deadcode is unavailable, package loading fails, or the check would require environment changes, record that it was skipped and why. Only report dead-code findings that are source-verified and introduced or exposed by the branch.
Before launching agents, build a concise review context and pass it to every agent. Show the context as a table before launching agents so assumptions are visible:
Context
Source
Value
User goal
Conversation
One-line summary, or not provided
Implementation plan
Conversation / docs
One-line summary, or not provided
PR context
PR title/body
One-line summary, or no PR found
Commits
git log --oneline origin/main..HEAD
One-line summary of commit intent
Changed surface
Assistant
Using pfleidi:review for the requested branch review. I’ll follow its default path: diff against origin/main, launch parallel review agents, then autofix only high-confidence Required findings if any.
Assistant
I’m refreshing origin/main first so the review base is the current remote ref, then I’ll collect the branch diff, PR context, and Go dead-code signal.
Assistant
git fetch origin main completed, but it only reported FETCH_HEAD; I’m fetching the remote normally as well so origin/main itself is definitely refreshed before the diff.
Assistant
Now I’m collecting the review surface: full diff against origin/main, branch commits, PR text, and the dead-code check required for Go diffs.
Assistant
Changed files against origin/main: 4 Go files in cmd/entire/cli/checkpointpolicy. deadcode is not installed, so that check is skipped as tooling unavailable; I’m checking PR metadata through the repo API since gh pr view cannot infer the custom remote host.
Assistant
The PR lookup failed because zsh treated the ?head=... query as a glob. I’m rerunning it quoted, then I’ll start the review agents.
Assistant
Review surface against origin/main: 4 changed files total.
File
Status
cmd/entire/cli/checkpointpolicy/format.go
M
cmd/entire/cli/checkpointpolicy/format_test.go
M
cmd/entire/cli/checkpointpolicy/remote.go
M
cmd/entire/cli/checkpointpolicy/update_test.go
M
Context
Source
Value
User goal
Conversation
Review this branch with pfleidi:review; latest committed checkpoint adds SemVer checkpoint policy parsing.
Implementation plan
Conversation/checkpoint
Use golang.org/x/mod/semver; keep read/write support exact; add downgrade tests; preserve policy behavior.
PR context
gh api
no PR found for checkpoint-policy-command-semver
Commits
git log --oneline origin/main..HEAD
SemVer support plus adoptRemoteBaseline helper extraction, with main merges.
Changed surface
diff file list
checkpointpolicy format parsing/comparison, remote sync helper extraction, related tests.
Go dead-code check
deadcode -test ./...
skipped: deadcode command not found
Inferred behavior
commits/tests/checkpoint
Checkpoint policy versions now canonicalize through SemVer; downgrade checks catch minor/patch/prerelease ordering; remote sync adopts remote baseline via a helper.
I’m launching the review agents now: security, correctness, simplification, readability, and clean Go.
Assistant
The five first-pass agents are running. While they work, I’m doing my own narrow pass over the changed package and call sites so I can verify or discard their findings instead of forwarding raw agent output.
Assistant
My local pass is focused on two risk points: whether SemVer canonicalization changes persisted policy text in surprising ways, and whether the helper extraction in Sync preserved Source/RemoteHash behavior. Next I’m collecting the agent results.
User
<subagent_notification>
{"agent_path":"019f0536-fd9d-7fa2-be14-c0375799e526","status":{"completed":"No security findings.\n\nReviewed the live git diff origin/main for the 4 changed files and traced the changed paths through policy flag input, remote policy.json reads, SemVer parsing/comparison, remote sync adoption, and the git remote wrapper. I did not find confirmed injection, traversal, TOCTOU, auth/authz, secret leakage, or unvalidated-boundary issues introduced by this diff."}}
</subagent_notification>
Assistant
Security came back clean. I’m waiting for the remaining first-pass agents before launching the independent coverage sweep.
Correctness found no issues. One clean-Go pass remains.
User
<subagent_notification>
{"agent_path":"019f0537-0746-7323-a1ad-2adeb79c1cd6","status":{"completed":"No findings.\n\nReviewed the current git diff origin/main for the four changed checkpointpolicy Go files. Target Go version is 1.26.4; I traced ParseFormat, Compare, CheckpointFormat.String, and adoptRemoteBaseline through their call sites and checked the related tests. No confirmed clean-Go, modern-Go, or testing-scope issues."}}
</subagent_notification>
Assistant
All first-pass agents are clean. I’m launching the second-pass coverage sweep now, independently, to catch anything the lens passes may have missed.
Assistant
While the coverage agent runs, I’m checking the exact line numbers and branch status for the final report, and whether a project-local ignored tmp/ exists in case fixes are needed.
Assistant
A small point I’m checking locally: the new parser splits the family and version at the first dash. I’m searching docs/tests for whether checkpoint family names are expected to allow dashes before deciding if that is a real finding or just speculation.
The independent coverage sweep also found no issues. I’m closing the completed review agents and doing the completion check before I report the clean review.
Assistant
Review is clean against origin/main.
Covered 4 changed files in cmd/entire/cli/checkpointpolicy:
format.go
format_test.go
remote.go
update_test.go
Results:
Security: no findings
Correctness/quality: no findings
Simplification/efficiency: no findings
Readability/Go idioms: no findings
Clean Go/modern Go: no findings
Independent coverage sweep: no findings
deadcode -test ./... was skipped because deadcode is not installed. No Required findings, no Improvement findings, no autofixes applied, no commits made.
User
I've just installed deadcode
Assistant
Using pfleidi:review as a continuation of the skipped dead-code step. I’ll run deadcode -test ./... now and only treat source-verified, branch-relevant output as review findings.
Assistant
deadcode -test ./... now runs, but it reports broad pre-existing unreachable symbols outside this diff. I’m rerunning it scoped to the touched package so the review signal is branch-relevant.
Assistant
The package-only run reports checkpointpolicy entry points as dead because deadcode only starts from executable packages. I’m rerunning with the CLI executable as the root and filtering output to checkpointpolicy, which is the branch-relevant shape.
Assistant
The executable-only run still misses the package’s own external tests, so it flags String even though the package test suite exercises it. I’m doing the final scoped form over ./... with the same package filter.
Assistant
Dead-code check is now accounted for.
Evidence:
Command
Exit
Relevant output
deadcode -test ./...
0
Broad pre-existing findings outside this branch surface, mostly benchutil, e2e, and unrelated internals.
I also checked the narrower package/executable forms; they can produce false positives because deadcode only starts from executable/test roots in specific ways. The branch-relevant filtered ./... run is the useful signal here.
Review result remains: no Required findings, no Improvement findings, no fixes applied, no commits made.
User
Are there any docs and/or command help text that needs to be updated in order to show that you can use semver versions now?
Assistant
Using using-entire because this is codebase exploration against the checkpoint-policy branch; I’ll check current docs/help strings and distinguish what’s required from optional clarity updates.
Assistant
I’m checking both user-facing command strings and repo docs now. The key distinction is whether the old branch-v1 examples are still correct versus whether they now under-document accepted aliases like branch-v1.2.3.
Assistant
The only docs hit is the checkpoint metadata JSON example, not a policy-command doc. I’m narrowing to docs and command help text so the answer doesn’t get muddied by tests and implementation strings.
Assistant
Yes, I’d update two places.
Checkpoint-backed intent from 5b9a51224543: SemVer is for parsing/comparison, while read/write support remains explicit. So docs/help should avoid implying every branch-v1.2.3 value is currently writable.
Recommended updates:
cmd/entire/cli/checkpoint_policy.go: flag help is too vague. It should say the version is a checkpoint format like branch-v1 or branch-v1.0.0, and maybe that supported values are still CLI-gated.
docs/architecture/sessions-and-checkpoints.md: the JSON example with "checkpoint_version": "branch-v1" is still correct, but the surrounding format docs should mention that checkpoint format versions are parsed as SemVer after the family prefix, with branch-v1 canonicalizing to branch-v1.0.0.
I would not add broad user docs yet unless the hidden entire checkpoint policy command is being made discoverable. A narrow architecture note plus clearer hidden-command help is enough.
User
Do it
Assistant
Using brainstorming lightly because this is user-facing wording, but this is a small targeted change so I’ll execute directly: update hidden command help and the architecture note, with a focused test if the local test shape supports it.
Assistant
I’ve got the scope: two files plus one focused help test. I’m updating the hidden command’s help to name the accepted format shape without promising unsupported versions are writable, and adding an architecture note near the metadata example.
Assistant
The command help now has the SemVer shape and support caveat. I’m adding the matching help-output test before touching the docs.
Assistant
The help test keeps the expected wording pinned without coupling to the whole help output. I’m adding a short architecture note beside the checkpoint metadata example now.
Assistant
The edits are in place. I’m formatting the Go files, then I’ll run the focused command tests plus build and lint for the changed CLI code.
Assistant
gofmt completed with no output. I’m running the verification batch now from the formatted tree.
Assistant
Verification passed. I’m reviewing the final diff and status now so I can report exactly what changed and avoid claiming anything outside this small help/docs update.
Assistant
A new unrelated modification in cmd/entire/cli/agentimport/agentimport.go is present in the worktree; I did not touch it. Since it appeared in the same Go tree, I’m rerunning the build/lint checks once more so the verification I report matches the current state.
Assistant
The fresh lint run fails on the unrelated agentimport.go change, not on the help/docs update. I’m reading that small diff only to make sure the failure is correctly attributed before I report status.
Assistant
Applied the docs/help update.
Changed:
checkpoint_policy.go: help now explains checkpoint formats as family prefix + SemVer, gives examples, and states read/write support remains explicit.
checkpoint_policy_test.go: added a focused help-output test.
sessions-and-checkpoints.md: added the architecture note beside the metadata example.
Verification:
Command
Exit
Output
go test ./cmd/entire/cli -run 'TestCheckpointPolicyCmd_' -count=1
0
ok github.com/entireio/cli/cmd/entire/cli 1.154s
go build ./cmd/entire
0
no output
mise run lint
1
Fails on unrelated agentimport.go: missing //nolint:ireturn on Get
I did not touch cmd/entire/cli/agentimport/agentimport.go; it is an unrelated existing worktree change. Current tree is not lint-clean until that unrelated lint issue is handled.
User
commit the changes
Assistant
I’ll commit only the three files I changed for the SemVer help/docs update and leave the unrelated agentimport.go edit unstaged. I’m refreshing the scoped diff first so the commit message matches the actual staged work.
Assistant
The scoped diff is just the help/docs update. The focused test and build passed after these edits; mise run lint failed only because the unrelated agentimport.go change removed an existing //nolint:ireturn. I’m staging only my three files and committing them now.
Assistant
Commit succeeded. I’m checking the final status so I can confirm only the unrelated file remains modified.
Assistant
Committed the help/docs update as:
196a351317 document checkpoint format versions
Included only:
cmd/entire/cli/checkpoint_policy.go
cmd/entire/cli/checkpoint_policy_test.go
docs/architecture/sessions-and-checkpoints.md
Verification before commit:
go test ./cmd/entire/cli -run 'TestCheckpointPolicyCmd_' -count=1 exit 0
go build ./cmd/entire exit 0
mise run lint exit 1 due to unrelated cmd/entire/cli/agentimport/agentimport.go
Current status: branch is ahead by 1 commit, with only the unrelated agentimport.go modification remaining unstaged.
PrePush hook can push entire/checkpoints/v1 branch alongside user pushes
OPF (OpenAI Privacy Filter) runs at pre-push, not post-commit: when redaction.openai_privacy_filter.enabled is true, the PrePush hook re-redacts unpushed entire/checkpoints/v1 commits with the OPF 8th layer, builds new commits carrying an Entire-OPF-Applied: true trailer, and atomically updates the local v1 ref before pushing. Per-commit condensation stays on the fast 7-layer pipeline. See strategy/manual_commit_opf_rewrite.go and docs/security-and-privacy.md for the full flow, including divergence detection, bootstrap caps, and CAS-on-conflict semantics.
Safe to use on main/master since it never modifies commit history
diff file list
Main packages/files touched
Go dead-code check
deadcode -test ./...
Findings summary, skipped: reason, or n/a
Inferred behavior
commits/tests/docs/user text
Intended behavior change, or diff-only inference
The user's request and any implementation plan, design notes, or acceptance criteria provided in the conversation.
Branch commit messages from git log --oneline origin/main..HEAD.
PR title/body when a PR exists for the branch.
The changed-file list and any obvious intended behavior changes inferred from commits, tests, docs, or user-facing text.
Treat this context as the statement of intent. If no implementation plan or PR context exists, say that intent is inferred from the diff and commits only.
2. Spawn Parallel Review Agents
Review Philosophy
Pass these rules to every agent:
It is OK to find nothing. A clean review is a valid outcome. Do NOT manufacture findings to justify the review. Only flag issues you are confident are real problems.
Be opinionated and consistent. If a pattern is acceptable, don't flag it. If you flag something, commit to that position — don't suggest the opposite approach on a re-review.
Don't flag trade-offs with no clear winner. If there are two reasonable approaches and neither is clearly better, don't flag it. The author already made a choice.
High confidence only. Every finding must pass the bar: "I am confident this is a problem, and I can explain specifically what goes wrong if it's not fixed." Vague unease is not a finding.
Permission-friendly reads. Avoid shell pipelines, command separators, subshells, and output filters for read-only investigation because they create extra permission prompts and block background review agents. Do not run commands like git show HEAD:path | sed -n '10,40p'. Use workspace file range reads, rg with path limits, path-scoped git diff $BASE -- <path>, or one standalone git show <rev>:<path> only when the output is acceptably small.
Intent-aware review. Review changed code against the review context, not against the old behavior alone. Do not classify an intentional behavior change as Required merely because it differs from origin/main. A Required finding must either contradict stated intent, break an existing contract that the intent did not change, introduce a concrete bug/security issue, or leave the intended behavior unverified in a way that would likely fail.
Launch four baseline sub-agents in parallel using the Agent tool. Pass each agent origin/main as the base ref, the full list of changed files, the review context, and the review philosophy above.
When the repository is a Go project and the diff includes Go-related files (*.go, go.mod, or go.sum), also launch Agent 5 in the same batch. Do not run the Go-specific agent for non-Go diffs.
Secrets or credentials — hardcoded tokens, leaked keys, credentials in code or config
For EACH finding: read the actual source file and trace whether the code path is reachable in production. Discard any finding you cannot confirm with a concrete code reference.
Redundant state — state that duplicates existing state, cached values that could be derived
Production test seams — mutable function variables, package-wide settings, reset hooks, or exported knobs added only so tests can swap behavior instead of using dependency injection or a higher-scope test
Parameter sprawl — adding new parameters instead of restructuring
Stringly-typed code — using raw strings where constants or typed values already exist in the codebase
Test coverage and scope gaps — changed behavior, edge cases, or error paths not exercised by meaningful tests; tests that prove implementation details instead of behavior; or unit tests used where integration/e2e coverage is the right confidence boundary
Test helper over-abstraction — helpers that hide the behavior, expected values, or assertions and make the test harder to understand than a small amount of duplication
For EACH finding: verify the claim by reading the source. Check call sites to confirm the issue is real, not hypothetical.
Agent 3: Simplification & Efficiency
Review git diff $BASE for:
Dead code — unreachable branches, unused functions, struct fields that are never read
Code reuse — search for existing utilities and helpers that could replace newly written code; flag duplicated functionality
Copy-paste with variation — near-duplicate blocks that should be unified
Unnecessary abstractions — wrapper types, indirection, or overly defensive fallbacks that mask errors
Unnecessary work — redundant computations, repeated file reads, duplicate API calls, N+1 patterns
Missed concurrency — independent operations run sequentially when they could be parallel
Hot-path bloat — blocking work added to startup or per-request paths
Unnecessary existence checks — pre-checking file/resource existence before operating (TOCTOU anti-pattern); operate directly and handle the error
Unnecessary comments — comments explaining WHAT the code does (well-named identifiers already do that); keep only non-obvious WHY
Use the deadcode -test ./... result when available, but do not trust it blindly: verify any reported unreachable function against the diff, call sites, and intended entry points before making it a finding.
For EACH suggestion: verify it does not break existing behavior by checking call sites and usages. Discard cosmetic-only suggestions (renames, formatting).
Agent 4: Readability & Go Idioms
Review git diff $BASE for code that is hard to read, maintain, or reason about:
Poor factoring — functions doing multiple jobs, tangled control flow, or missing helper extraction where a small local helper would clarify behavior
Mixed abstraction levels — high-level orchestration mixed with low-level IO, parsing, protocol, or data-structure details; low-level helpers that also make workflow or policy decisions
Generated-code smell — repetitive pasted logic, shallow wrappers, generic names, or code that reads like it was assembled without domain intent
Data-flow opacity — values transformed across too many steps, unclear ownership, hidden mutation, pass-through helper chains, or state threaded through unrelated code
Control-flow complexity — deeply nested conditionals, boolean flag plumbing, early returns used inconsistently, or error paths that obscure the main path
Naming clarity — names that hide domain meaning or force callers to inspect implementation to understand usage
Go API readability — ambiguous (result, bool) returns outside clear comma-ok/presence checks, oversized interfaces, unnecessary pointer indirection, or cleverness where explicit Go would be clearer
Error readability — errors that lose operation/context, wrap inconsistently, or make call sites branch on strings/booleans instead of clear errors or typed status
For EACH finding: explain the readability cost in concrete maintenance terms. Prefer small, local refactor suggestions. Discard formatting-only, gofmt-only, or personal taste comments.
Agent 5: Clean Go & Modern Go (Go diffs only)
Use the local pfleidi:clean-go skill as the source of truth: skills/pfleidi/clean-go/SKILL.md.
Review only changed Go code plus surrounding source, tests, interfaces, and call sites needed to verify findings. Apply the skill's Clean Go checks and version-gated Modern Go checks. This includes the modern-go guidance incorporated from JetBrains' use-modern-go skill: detect the relevant go.mod target version, only suggest features available for that version, and do not perform blanket modernization.
Focus on concrete changed-code findings around composable functions, abstraction level, function size/signatures, errors, pointers, small interfaces, any/interface{}, testing guidance from skills/pfleidi/testing/SKILL.md, and modern standard-library helpers. Discard findings that would merely restyle existing code or require a broad rewrite unrelated to the current diff.
Second-Pass Coverage Sweep
After the first-pass agents complete, run a second independent review pass before synthesis. The goal is recall: catch high-confidence findings that the lens-specific agents may have missed.
Launch one fresh coverage agent with origin/main as the base ref, the full list of changed files, the review context, and the review philosophy above. Do not pass the first-pass findings to this agent.
Ask the coverage agent to:
Re-read the changed files and the surrounding code needed to understand each changed path.
Trace changed behavior through callers, callees, tests, configuration, migrations, generated interfaces, and user/API entry points where relevant.
Search the repository for related patterns, duplicated logic, and existing helpers that affect the changed code.
Look across all lenses together: security, correctness, tests, simplification, readability, performance, and Go cleanliness when applicable.
Re-check Go dead code from the deadcode -test ./... result when available, and search manually for obvious unreachable additions when it was skipped.
Prioritize missed Required findings over optional improvements.
Return only high-confidence findings with concrete file:line evidence and a short explanation of the traced path.
Then compare the second-pass findings with the first-pass findings. Deduplicate overlaps, verify any new claim by reading source yourself, and discard anything that cannot be confirmed.
3. Synthesize Report
After all launched agents complete:
Collect findings from both the first-pass agents and the second-pass coverage sweep
Deduplicate — merge findings from different agents that point to the same underlying issue
Verify — for any finding where the agent did not cite a specific file:line with evidence, read the source and confirm or discard it
Group by file
Sort by severity within each file: Critical > High > Medium > Low
Severity Definitions
Critical — Must fix before merge. Bugs, security vulnerabilities, data loss risk, race conditions with observable impact.
High — Should fix before merge. Missing error handling, meaningful test gaps, performance issues on hot paths.
Medium — Worth fixing. Code reuse opportunities, unnecessary complexity, readability problems that make future changes error-prone, minor efficiency improvements.
Low — Optional. Minor readability improvements or cosmetic suggestions.
Relevance Classification
For each finding, classify as:
Required — The change does not work correctly without this fix in light of the review context. Bugs, missing error handling that causes failures, security vulnerabilities, race conditions, contradictions of stated intent, or missing tests for intended behavior that would likely fail. The branch should not merge without addressing these.
Improvement — Valid finding, but the change works correctly without it. Better factoring, clearer Go APIs, using existing helpers, code reuse, unnecessary complexity, style. Worth addressing in a follow-up, not in this branch.
Autofix Eligibility
Mark each Required finding as Autofix eligible or Needs decision:
Autofix eligible — source-backed, high confidence, minimal fix is clear, no new dependencies, no shared/public interface change, no product/design choice, no broad refactor, and the directly related verification path is clear.
Needs decision — any Required finding that fails one of the autofix checks, including intentional behavior questions, API shape changes, cross-cutting refactors, or fixes where multiple reasonable approaches exist.
Present findings as compact tables, not prose blocks. Use one summary table for scanning and one details table for evidence and fixes.
Summary table format:
#
Severity
Sources
Location
Classification
Autofix
Issue
Impact
1
Medium
correctness + coverage
cmd/entire/cli/checkpoint/v2_committed.go:234
Required
Eligible
One-sentence problem.
Concrete consequence if not fixed.
Details table format:
#
Evidence
Suggested fix
Trade-offs
1
Source-backed confirmation from code path, call site, or test gap.
Concrete code change, not vague advice.
One sentence, or None if strictly better.
Keep table cells short and scannable. Put the smallest useful quote or evidence in the table rather than full paragraphs. Escape | characters inside code or text so the table remains valid Markdown. Use n/a for Autofix on Improvements. The Sources column lists the agents that independently found or confirmed the issue, such as security, correctness, readability, clean-go, or coverage.
If no findings exist at a severity level, omit that section.
If there are 0 findings across all agents, report that the review is clean and stop.
4. Present Report and Proceed With Default Fixes
Present findings in two sections:
Required
Table of findings classified as Required, sorted by severity. Include the Autofix value for each finding. Follow it with the details table for those same Required findings.
Improvements (follow-up)
Table of findings classified as Improvement, continuing the numbering. These are presented for awareness but are NOT included in the fix cycle by default. Follow it with the details table for those same Improvement findings.
End with a one-paragraph summary: total required vs improvement findings, overall merge-readiness assessment, and any patterns across files.
Before editing, present a planned-autofix table for Autofix eligible Required findings:
#
Location
Planned change
Related test/verification
Files expected
1
path/file.go:42
Minimal code change to address the finding.
Focused test or lint/build command.
path/file.go, path/file_test.go
Do not ask the user to choose a mode. Immediately proceed to Step 5 for Autofix eligible Required findings after showing the planned-autofix table. Do not fix Improvements by default.
If there are Required findings but none are Autofix eligible, stop after the report and list the exact decisions needed.
5. Fix Cycle
Scope Rules
Make the MINIMAL change that addresses the finding
Keep the diff limited to files and lines directly required by the finding
First decide whether the finding is local or systemic. Fix at the narrowest correct level; do not add a local workaround that hides a shared/root-cause bug.
If the finding requires a behavior-changing code fix, add or update the directly related test in the same fix step. Prefer TDD, but complete the focused red-to-green cycle before stopping: write/update the failing test, confirm it fails, implement the fix, confirm the focused test passes. Do not stop after only adding the failing test unless the user explicitly asks.
Do NOT rename variables, reformat code, or touch lines outside the finding scope
Do NOT refactor adjacent code, even if it looks related
Do NOT create any git commits — code changes only
Default Batched Fixes
Fix all Autofix eligible Required findings in report order by default. Do not ask which findings to fix.
Choose an artifact directory using the AGENTS.md temporary artifact rule with agent name pfleidi-review:
Use ./tmp/pfleidi-review/ only when ./tmp/ already exists and is already ignored.
If no project-local artifact directory is available, do not create file artifacts by default; keep ledger/log/cache information in the response and mark file paths n/a. Ask before using /tmp/pfleidi-review/ or modifying ignore files.
When an artifact directory is available, create a temporary fix ledger at <artifact-dir>/review-<repo-name>-<timestamp>.md before editing. If no artifact directory is available, keep the same ledger fields in the final summary table instead. Update the ledger after each finding with:
Finding number, status, and source location.
Files touched.
What changed and why.
Related tests or verification commands.
Rollback notes sufficient for the user to understand how to revert the finding-specific change manually.
For each Autofix eligible finding:
Read the relevant code to confirm the fix approach
Re-check eligibility before editing; if the fix is no longer clearly eligible, mark it Needs decision and continue to the next finding
Implement the fix — ONLY the code changes for that single finding
Add or update the directly related test in the same diff when the fix changes behavior; if using TDD, complete red-to-green before moving on; if no test is added, state why
Keep the diff limited to files and lines directly required by that finding
If a fix would require changing a function signature in a shared interface, adding a dependency, expanding scope outside the finding, or making an ambiguous product/design choice, skip that finding as Needs decision and continue
Track the exact files changed, what changed, and why the change addresses the finding
If a skipped finding has partial edits, remove only your own partial edits for that finding before continuing. If you cannot safely isolate those partial edits, stop and explain the conflict.
After all eligible fixes are applied, proceed directly to Step 6 (Verify Fixes). Do NOT show a diff yet.
6. Verify Fixes
Run the project's compile/build, lint, and test commands scoped to only the changed files and their directly related tests. Use safe background batches for independent validators instead of running every command sequentially.
When selecting verification commands, reuse <artifact-dir>/verification-<repo-name>.md if an artifact directory is available and the cache is fresh under the cache rules from pfleidi:pr; otherwise discover the smallest relevant lint/test/build commands. Update the cache only when an artifact directory is available.
Build / compile — run a relevant compile/build command when one is discoverable for the changed production code.
Lint / static analysis — run the project's documented lint task, scoped to the files that were modified by the fixes when the task supports scoping. Prefer lint-specific task wrappers such as make lint or mise run lint over invoking linter binaries directly. Do not use aggregate check, ci, or verify tasks unless you have confirmed they only run lint/static analysis. If the documented lint task cannot be scoped, run the smallest relevant project lint task.
Tests — run only the test files that cover the modified code (same package, same module, co-located test files). Do NOT run the full test suite.
If no compile/build command or project lint task exists, state that explicitly instead of assuming an unavailable command.
Run formatters, generators, snapshot updates, or other mutating commands alone before validators that depend on their output. Run independent read-only validators concurrently when they do not require the same exclusive service, port, database, fixture directory, or generated output. Keep integration/e2e/service-backed commands separate unless the project documents that they are parallel-safe.
For each background batch, start every command from the same working-tree state, capture stdout/stderr/exit status from the tool, do not edit files while the batch is running, and wait for every command to finish. Run each selected validator directly, for example mise run lint, go test ..., or npm test -- .... Do not wrap validators in sh -c, shell redirection, tee, command separators, or pipelines solely to write logs; that defeats command-prefix approvals and causes extra permission prompts. If an artifact directory is available and file logs can be written after the command completes without rerunning through a shell wrapper, save them under <artifact-dir>/logs-<repo-name>-<timestamp>/; otherwise mark the full-log path as n/a. If files change after a failed batch, none of that batch's successful results count as current verification.
Show verification as a compact table:
Command
Exit
Relevant output
Full log
go test ./pkg/foo -run TestBar -count=1
0
Short success excerpt.
<artifact-dir>/logs-.../go-test-pkg-foo.log or n/a
For failures or short outputs, show complete output in the relevant-output column or immediately below the table. For long successful outputs, show the relevant excerpt and log path.
On Failure: Auto-Fix
If compile/build, lint, or tests fail due to issues introduced by the review fixes:
Read the error output and identify every failure
Fix all issues — apply the minimal changes needed
Re-run the failing commands using the same safe batching rules
Show the complete output again
Cap at 2 fix attempts. If still failing after 2 rounds, present the remaining failures to the user with full output. Do not describe the work as done or commit-ready while compile/build status is failing or unknown for changed production code.
7. Present Results
Once verification passes (or the user has seen the remaining failures), present a summary table. If compile/build did not pass for code changes, say the work is not commit-ready before the table. Do NOT show a diff — the Edit tool already showed each change inline.
#
Finding
File
Status
What changed
Why
1
Description
path:line
Fixed
Added nil check in foo
Prevents panic on missing config
3
Description
path:line
Fixed
Added focused test for invalid input
Verifies intended error path
6
Description
path:line
Needs decision
None
API shape has two reasonable options
Also present a rollback/traceability table and the ledger path:
#
Files touched
Rollback notes
1
path/file.go, path/file_test.go
Revert the nil-check and focused test added for finding #1.
Ledger: <artifact-dir>/review-<repo-name>-<timestamp>.md, or n/a when no project-local artifact directory was available.
STOP and wait. The user decides what to commit.
8. Post-Fix
If the user asks for changes, apply them
If the user asks to revert specific fixes, revert ONLY those changes using surgical git checkout of the affected lines
Do NOT commit. The user handles commits on their own terms.