Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion docs/src/content/docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ The command uses the same service and safety contract as `no-mistakes axi sync`,

## no-mistakes status

Show repo, daemon, active run, and relevant cached local-branch synchronization status.
Show repo, daemon, active run, and cached local-branch synchronization status.

```sh
no-mistakes status
Expand All @@ -372,6 +372,16 @@ Displays:
- Gate path
- Daemon status (running/stopped, PID)
- Active run details: ID, branch, status, head SHA, start time
- Cached local repository state: branch, short `HEAD`, cleanliness, and the
locally recorded synchronization guidance

The cached local-state line is always present once a repository is registered.
It is local evidence only: its Git inspection does not fetch or query a Git
remote, and it does not claim that the remote branch is currently fresh. That
inspection does not mutate the local Git object database, refs, index, or
worktree; a Git-status failure is labelled as unavailable rather than as
confirmed dirtiness. `status` may still record its normal local command
telemetry separately.

## no-mistakes runs

Expand Down
191 changes: 191 additions & 0 deletions docs/superpowers/plans/2026-08-26-cached-repository-state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
# Cached Repository State Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Make `no-mistakes status` always render cached, local-only repository branch evidence without adding a pipeline or network operation.

**Architecture:** `internal/cli/status.go` already obtains `branchsync.State` through `InspectCached`. Add one small presenter for that state and render it unconditionally after repository discovery. Include the rendered cached summary in the existing status telemetry fingerprint so sampled status events correspond to visible state.

**Tech Stack:** Go, Cobra, existing `branchsync.Service`, existing CLI test helpers.

---

## File structure

- Modify: `internal/cli/status.go` - render cached evidence and fingerprint it.
- Create: `internal/cli/status_test.go` - table tests for the pure cached-state presenter and fingerprint coverage.

### Task 1: Write the failing presenter test

**Files:**

- Create: `internal/cli/status_test.go`

- [ ] **Step 1: Define clean, dirty, and unavailable cases**

```go
func TestCachedBranchSummary(t *testing.T) {
tests := []struct { name string; state branchsync.State; want string }{
{"clean branch", branchsync.State{State: branchsync.StateSynchronized, Local: branchsync.LocalState{Branch: "feature/state", Head: "0123456789abcdef", Clean: true}}, "cached: feature/state 01234567 (clean; already synchronized with the pipeline-pushed head)"},
{"dirty branch", branchsync.State{State: branchsync.StateDirty, Local: branchsync.LocalState{Branch: "feature/state", Head: "fedcba9876543210", Reason: "uncommitted changes"}}, "cached: feature/state fedcba98 (dirty: uncommitted changes; dirty)"},
{"unavailable", branchsync.State{State: branchsync.StateAmbiguousContext}, "cached: unavailable (ambiguous context)"},
}
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {
if got := cachedBranchSummary(tt.state); got != tt.want { t.Fatalf("cachedBranchSummary() = %q, want %q", got, tt.want) }
}) }
}
```

- [ ] **Step 2: Verify red**

Run: `go test ./internal/cli -run '^TestCachedBranchSummary$'`

Expected: compile failure because `cachedBranchSummary` does not exist.

### Task 2: Add the local-only presenter and render it

**Files:**

- Modify: `internal/cli/status.go`
- Test: `internal/cli/status_test.go`

- [ ] **Step 1: Implement the presenter**

```go
func cachedBranchSummary(state branchsync.State) string {
summary := humanSyncSummary(state)
if state.Local.Branch == "" || state.Local.Head == "" { return "cached: unavailable (" + summary + ")" }
head := state.Local.Head[:minLen(len(state.Local.Head), 8)]
cleanliness := "clean"
if !state.Local.Clean { cleanliness = "dirty"; if state.Local.Reason != "" { cleanliness += ": " + state.Local.Reason } }
return fmt.Sprintf("cached: %s %s (%s; %s)", state.Local.Branch, head, cleanliness, summary)
}
```

- [ ] **Step 2: Replace the conditional cached-state rendering**

```go
syncState := (&branchsync.Service{DB: d, Repo: repo, WorkDir: "."}).InspectCached(cmd.Context())
cachedSummary := cachedBranchSummary(syncState)
fmt.Fprintf(w, "\n %s %s\n", sDim.Render("local state:"), cachedSummary)
```

- [ ] **Step 3: Verify green**

Run: `go test ./internal/cli -run '^TestCachedBranchSummary$'`

Expected: PASS.

### Task 3: Keep telemetry aligned with rendered evidence

**Files:**

- Modify: `internal/cli/status.go`
- Modify: `internal/cli/status_test.go`

- [ ] **Step 1: Add a failing fingerprint regression test**

```go
func TestStatusFingerprintIncludesCachedSummary(t *testing.T) {
run := &db.Run{ID: "run-1", Branch: "feature/test", Status: "running", HeadSHA: "head-one"}
before := statusFingerprint("repo", "running", run, "cached: main 01234567 (clean; synchronized)")
after := statusFingerprint("repo", "running", run, "cached: main 89abcdef (dirty; dirty)")
if before == after { t.Fatal("changing displayed cached evidence must change the status fingerprint") }
}
```

- [ ] **Step 2: Verify red**

Run: `go test ./internal/cli -run '^TestStatusFingerprintIncludesCachedSummary$'`

Expected: compile failure until `statusFingerprint` accepts the cached summary.

- [ ] **Step 3: Update signature and call site**

```go
fingerprint := statusFingerprint(repo.ID, daemonState, activeRun, cachedSummary)
```

Build the fingerprint from repository id, daemon state, cached summary, and
the existing active-run fields. Update the existing active-run-head test with
the fourth argument.

- [ ] **Step 4: Verify focused tests**

Run: `go test ./internal/cli -run 'Test(CachedBranchSummary|StatusFingerprint)'`

Expected: PASS.

### Task 4: Validate and prepare review

**Files:**

- Modify: `internal/cli/status.go`
- Create: `internal/cli/status_test.go`

- [ ] **Step 1: Add command-level status coverage**

Use `setupTestRepo`, `executeCmd("init")`, and `executeCmd("status")` to
assert the clean and a newly dirty worktree both retain `repo`, `daemon`, and
`no active run` output and always include `local state: cached:`. The clean
case must include `(clean;`; the dirty case must include `(dirty:`.

Run: `go test ./internal/cli -run '^TestStatusAlwaysRendersCachedLocalState$' -count=1`

Expected: PASS.

- [ ] **Step 2: Format and run full gates**

Run: `gofmt -w internal/cli/status.go internal/cli/status_test.go && make lint && go test -race ./... && go build -o ./bin/no-mistakes ./cmd/no-mistakes`

Expected: each command exits 0.

- [ ] **Step 3: Inspect the review diff**

Run: `git diff --check && git diff -- internal/cli/status.go internal/cli/status_test.go`

Expected: no whitespace errors and no source file outside the planned scope.

- [ ] **Step 4: Commit after fresh evidence**

```bash
git add internal/cli/status.go internal/cli/status_test.go
git commit -m "feat(status): show cached repository state"
```

### Task 5: Review-remediation safety proof

**Files:**

- Modify: `internal/cli/status_test.go`
- Modify: `docs/src/content/docs/reference/cli.md`

- [x] **Step 1: Add a command-level cached-only safety regression**

Run `status` after `init` through a test-local Git wrapper that records any
`fetch` or `ls-remote` invocation. Snapshot `.git/FETCH_HEAD`, `.git/index`,
refs, worktree state, and the gate database before and after the command.
Assert that the command renders cached state, makes no remote Git call, and
does not change any snapshot. Also exercise a locally available diverged head
and snapshot `.git/objects`: cached inspection must conservatively report
`blocked_diverged` without constructing a merge tree.

- [x] **Step 2: State the user-facing freshness boundary**

Document that the always-rendered cached local-state line's Git inspection is
local evidence, does not fetch or query a Git remote, does not mutate local
Git state, and does not assert remote freshness. Existing command telemetry
is a separate concern. A Git-status failure must render cleanliness as
unavailable, never as a confirmed dirty worktree.

- [x] **Step 3: Run focused and full verification**

Run:

```bash
gofmt -w internal/cli/status_test.go
go test ./internal/cli -run 'TestStatus' -count=1
make lint && go test -race ./... && go build -o ./bin/no-mistakes ./cmd/no-mistakes && git diff --check
```

Expected: each command exits 0 before updating the PR.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Cached Repository State Design

## Intent

Rebuild the legitimate portion of the old fork's diagnostics intent on current
`upstream/main`: make `no-mistakes status` always show the already-available
local branch evidence that an agent needs before starting work.

## Scope

`status` will call the existing `branchsync.Service.InspectCached` once and
render a clearly labelled cached summary containing the local branch, a short
HEAD, clean/dirty state, any local reason, and the existing human branch-sync
summary. Its telemetry fingerprint will include that rendered evidence so a
meaningful displayed state change is observable by the sampled read surface.

## Safety contract

`InspectCached` is the data source because it explicitly does not fetch,
contact a remote, alter the Git object database, alter refs, alter the index,
alter the worktree, create a pipeline run, or mutate the database. It must
also report unavailable cleanliness as unavailable rather than as confirmed
dirtiness. Semantic equivalence for diverged histories is deferred to an
explicit refresh, because Git's merge-tree proof can write an object. The
output must say `cached`; it must not claim current remote freshness.

## Non-goals

- No new pipeline step, daemon behaviour, schema, gate, worktree inventory,
remote inspection, or direct process execution.
- No recovery or synchronization action from `status`.
- No recovery of the fork's unregistered pipeline experiment or tracked binary.

## Acceptance criteria

1. A registered repository's `status` output always includes cached local
branch evidence, including an explicit unavailable form when Git evidence is
absent.
2. A clean and a dirty local state render distinguishable, actionable text.
3. A change to rendered cached state changes the status telemetry fingerprint.
4. Existing status behaviour for repo identity, daemon, and active-run display
remains intact.
5. `gofmt -w .`, `make lint`, `go test -race ./...`, and
`go build -o ./bin/no-mistakes ./cmd/no-mistakes` succeed before review.
18 changes: 9 additions & 9 deletions internal/branchsync/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,10 @@ func displayTarget(raw string) string {
return safeurl.Redact(raw)
}

// InspectCached reads local Git, persisted provenance, and read-only gate
// ancestry evidence without fetching or mutating refs, the index, or the
// worktree.
// InspectCached reads local Git and persisted provenance without fetching or
// mutating the Git object database, refs, index, or worktree. Semantic
// equivalence of diverged histories is intentionally deferred to Refresh,
// whose explicit operation may construct a temporary merge tree.
func (s *Service) InspectCached(ctx context.Context) State {
state, _, _ := s.inspect(ctx)
return state
Expand Down Expand Up @@ -1206,14 +1207,13 @@ func (s *Service) classifyRelation(ctx context.Context, state *State, pushed, ba
state.NextAction = &NextAction{Code: "run_pipeline", Command: `no-mistakes axi run --intent "<what the user set out to accomplish>"`}
return
default:
if equivalentDivergence(ctx, s.workDir(), state.Local.Head, pushed, base) {
// Equivalence uses `git merge-tree --write-tree`, which can add an
// object even though no ref or worktree changes. A cached inspection
// promises no local mutation, so reserve that proof for Refresh.
if live && equivalentDivergence(ctx, s.workDir(), state.Local.Head, pushed, base) {
Comment thread
greptile-apps[bot] marked this conversation as resolved.
state.State = StateDiverged
state.Relation = RelationDiverged
if live {
state.Safety = SafetySafeEquivalentAdvance
} else {
state.Safety = "refresh_required"
}
state.Safety = SafetySafeEquivalentAdvance
state.NextAction = &NextAction{Code: "sync", Command: "no-mistakes axi sync"}
state.Error = ""
return
Expand Down
49 changes: 49 additions & 0 deletions internal/branchsync/sync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -232,6 +233,54 @@ func TestInspectCachedBehindPerformsNoFetchOrMutation(t *testing.T) {
}
}

func TestInspectCachedDivergedDoesNotWriteGitObjects(t *testing.T) {
t.Parallel()

f := newSyncFixture(t)
rebuildPipelineHead(t, f, []pipelineCommit{
{message: "pipeline doc", files: map[string]string{"doc.txt": "pipeline doc\n"}},
})
mustRun(t, f.local, "fetch", f.remote, "refs/heads/feature/sync:refs/remotes/origin/feature/sync")

before := gitObjectFiles(t, f.local)
state := f.service.InspectCached(f.ctx)
after := gitObjectFiles(t, f.local)
if state.State != StateDiverged || state.Relation != RelationDiverged || state.Safety != "blocked_diverged" {
t.Fatalf("state = %#v", state)
}
if !reflect.DeepEqual(before, after) {
t.Fatalf("cached inspection wrote Git objects: before=%v after=%v", before, after)
}
}

func gitObjectFiles(t *testing.T, repoDir string) map[string]string {
t.Helper()
objects := filepath.Join(repoDir, ".git", "objects")
files := make(map[string]string)
err := filepath.WalkDir(objects, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
contents, err := os.ReadFile(path)
if err != nil {
return err
}
rel, err := filepath.Rel(objects, path)
if err != nil {
return err
}
files[rel] = string(contents)
return nil
})
if err != nil {
t.Fatalf("snapshot Git objects: %v", err)
}
return files
}

func TestApplyCleanStrictBehindFastForwardsExactBoundHead(t *testing.T) {
t.Parallel()

Expand Down
Loading