fix(show): preserve last-touched under --readonly (#5786)

* fix(show): preserve last-touched in readonly mode (#5785)

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* chore(bazel): enumerate last_touched_readonly_test.go in cmd/bd go_test srcs

adopt-pr maintainer fixup for PR #5786. The PR adds a new
//go:build cgo test file to cmd/bd; gazelle enumerates plain-cgo
test srcs unconditionally (330 of 645 enumerated srcs at the base
carry exactly that tag), so the new file is a real srcs-enumeration
gap. Produced by `make bazel-sync`; no hand-edits.

* fix(last-touched): guard ClearLastTouched, name both readonly triggers, add CHANGELOG entry

Maintainer review fixup for the adopt-pr review of #5786 (iteration 1,
synthesis approve, 0 blocker / 0 major).

- CHANGELOG: add the missing [Unreleased]/Fixed entry naming --readonly,
  bd show and .beads/last-touched, linking #5785. Anchored at the tail of
  the Fixed list rather than its top, which is where main appends.
- last_touched.go:65: the comment said "Strict --readonly", but the guard
  also fires when the flag is absent and readonly:true is set in config
  (main.go:1124 folds the config key into readonlyMode). Reworded to match
  the repo's canonical phrasing at serve.go:617-618.
- ClearLastTouched: take the same readonly early return. Removing the
  marker is as much a mutation of workspace-local state as writing it, so
  this makes the file's stated invariant true rather than narrowing the
  comment to match the gap. Zero production callers today (definition plus
  one non-readonly test caller), so no shipping behavior changes.

Declined, both non-gating and both "Required fix: None for merge": moving
the cmdCtx.ReadonlyMode write in PersistentPreRunE (serve.go:612-618
documents reading the global deliberately, and the divergence is latent
rather than live), and its conditional test arm, whose antecedent is false
once the hardening is declined.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
This commit is contained in:
ecuthiell 2026-09-29 19:17:57 -06:00 • committed by GitHub
commit 3f9561db2b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 212 additions and 1 deletions

View file

@ -314,6 +314,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`--format` now wins over the config default; an explicit `--json` still wins
over `--format`.
- **Strict readonly no longer records last-touched state**
([#5785](https://github.com/gastownhall/beads/issues/5785)). Under strict
readonly (`--readonly`, or `readonly` in config), `bd show` wrote the issue
id to `.beads/last-touched` even though readonly promises not to mutate
workspace-local state — the database store was opened read-only while this
marker file was still written. `SetLastTouchedID` now returns early in that
mode, so a readonly workspace leaves the marker untouched. Ordinary
(non-readonly) `bd show` keeps recording last-touched exactly as before, so
only consumers driving `bd --readonly … --json` see the change.
### Added
- **Auto-backup runs on a managed-local proxied-server workspace.** The

View file

@ -832,6 +832,7 @@ go_test(
"label_test.go",
"label_whitespace_warn_test.go",
"last_touched_guard_test.go",
"last_touched_readonly_test.go",
"last_touched_test.go",
"legacy_upgrade_guard_config_yaml_test.go",
"legacy_upgrade_guard_e2e_test.go",

View file

@ -62,7 +62,11 @@ func GetLastTouchedID() string {
// SetLastTouchedID saves the ID of the last touched issue.
// Silently ignores errors (best-effort tracking).
func SetLastTouchedID(issueID string) {
if issueID == "" {
// Strict readonly (--readonly, or readonly in config) promises not to
// mutate workspace-local state. Keep ordinary read commands writable here:
// `bd show` records last-touched by design even though its database store
// is opened read-only.
if issueID == "" || isReadonlyMode() {
return
}
@ -86,6 +90,14 @@ func SetLastTouchedID(issueID string) {
// ClearLastTouched removes the last touched file.
// Silently ignores errors.
func ClearLastTouched() {
// Same invariant as SetLastTouchedID: removing the marker is also a
// mutation of workspace-local state, so strict readonly must not do it.
// No production caller reaches here today, but guarding the sibling keeps
// the file's promise true if one is wired up later.
if isReadonlyMode() {
return
}
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return

View file

@ -0,0 +1,188 @@
//go:build cgo
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
type lastTouchedProcessResult struct {
stdout []byte
stderr []byte
exitCode int
}
func runLastTouchedProcess(t *testing.T, binPath, workDir string, args ...string) lastTouchedProcessResult {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
profileDir := t.TempDir()
env := make([]string, 0, len(os.Environ())+12)
for _, entry := range os.Environ() {
key, _, _ := strings.Cut(entry, "=")
lowerKey := strings.ToLower(key)
if strings.HasPrefix(lowerKey, "bd_") || strings.HasPrefix(lowerKey, "beads_") {
continue
}
switch lowerKey {
case "home", "userprofile", "appdata", "localappdata", "xdg_config_home":
continue
}
env = append(env, entry)
}
env = append(env,
"HOME="+profileDir,
"USERPROFILE="+profileDir,
"APPDATA="+filepath.Join(profileDir, "AppData", "Roaming"),
"LOCALAPPDATA="+filepath.Join(profileDir, "AppData", "Local"),
"XDG_CONFIG_HOME="+filepath.Join(profileDir, "xdg-config"),
"BEADS_TEST_MODE=1",
"BEADS_TEST_IGNORE_REPO_CONFIG=1",
"BEADS_TEST_CIRCUIT_DIR="+filepath.Join(profileDir, "circuit"),
"BEADS_NO_DAEMON=1",
"BD_DISABLE_METRICS=1",
"BD_DISABLE_EVENT_FLUSH=1",
"BD_NON_INTERACTIVE=1",
"LINEAR_API_KEY=",
"NO_COLOR=1",
)
cmd := exec.CommandContext(ctx, binPath, args...)
cmd.Dir = workDir
cmd.Env = env
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
t.Fatalf("bd %v timed out after 30s\nstdout: %s\nstderr: %s", args, stdout.String(), stderr.String())
}
exitCode := 0
if err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
t.Fatalf("bd %v in %s: %v\nstdout: %s\nstderr: %s", args, workDir, err, stdout.String(), stderr.String())
}
exitCode = exitErr.ExitCode()
}
return lastTouchedProcessResult{stdout: stdout.Bytes(), stderr: stderr.Bytes(), exitCode: exitCode}
}
func assertSuccessfulJSONShow(t *testing.T, result lastTouchedProcessResult, wantID string) {
t.Helper()
if result.exitCode != 0 {
t.Fatalf("show exit code = %d, want 0\nstdout: %s\nstderr: %s", result.exitCode, result.stdout, result.stderr)
}
var issues []struct {
ID string `json:"id"`
}
if err := json.Unmarshal(result.stdout, &issues); err != nil {
t.Fatalf("show stdout is not valid JSON: %v\nstdout: %s\nstderr: %s", err, result.stdout, result.stderr)
}
if len(issues) != 1 || issues[0].ID != wantID {
t.Fatalf("show JSON IDs = %+v, want exactly %q", issues, wantID)
}
}
func setLastTouchedSentinel(t *testing.T, path string, contents []byte) time.Time {
t.Helper()
if err := os.WriteFile(path, contents, 0o600); err != nil {
t.Fatalf("write last-touched sentinel: %v", err)
}
fixed := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC)
if err := os.Chtimes(path, fixed, fixed); err != nil {
t.Fatalf("set last-touched sentinel mtime: %v", err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatalf("stat last-touched sentinel: %v", err)
}
return info.ModTime()
}
func assertLastTouchedUnchanged(t *testing.T, path string, wantContents []byte, wantMtime time.Time) {
t.Helper()
gotContents, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read last-touched after readonly show: %v", err)
}
if !bytes.Equal(gotContents, wantContents) {
t.Fatalf("last-touched bytes changed after readonly show: got %q, want %q", gotContents, wantContents)
}
info, err := os.Stat(path)
if err != nil {
t.Fatalf("stat last-touched after readonly show: %v", err)
}
if !info.ModTime().Equal(wantMtime) {
t.Fatalf("last-touched mtime changed after readonly show: got %v, want %v", info.ModTime(), wantMtime)
}
}
// TestReadonlyShowPreservesLastTouched covers strict --readonly at the process
// boundary. A successful JSON read must preserve an absent marker and an
// existing marker byte-for-byte (including mtime). Ordinary show remains
// responsible for advancing the marker mtime even when it rewrites the same
// issue ID.
func TestReadonlyShowPreservesLastTouched(t *testing.T) {
binPath := buildBDUnderTest(t)
workDir := t.TempDir()
initBeadsWorkspace(t, binPath, workDir)
id := runBDStdout(t, binPath, workDir, "q", "readonly last-touched fixture")
if id == "" {
t.Fatal("bd q returned empty issue ID")
}
lastTouchedPath := filepath.Join(workDir, ".beads", lastTouchedFile)
t.Run("preserves absent marker", func(t *testing.T) {
if err := os.Remove(lastTouchedPath); err != nil && !os.IsNotExist(err) {
t.Fatalf("remove last-touched setup marker: %v", err)
}
result := runLastTouchedProcess(t, binPath, workDir, "--readonly", "show", id, "--json")
assertSuccessfulJSONShow(t, result, id)
if _, err := os.Stat(lastTouchedPath); !os.IsNotExist(err) {
t.Fatalf("readonly show created absent last-touched marker: stat error = %v", err)
}
})
sentinel := []byte("sentinel\r\nbytes\x00")
t.Run("preserves sentinel bytes and mtime", func(t *testing.T) {
mtime := setLastTouchedSentinel(t, lastTouchedPath, sentinel)
result := runLastTouchedProcess(t, binPath, workDir, "--readonly", "show", id, "--json")
assertSuccessfulJSONShow(t, result, id)
assertLastTouchedUnchanged(t, lastTouchedPath, sentinel, mtime)
})
t.Run("ordinary JSON show still advances marker mtime", func(t *testing.T) {
contents := []byte(id + "\n")
mtime := setLastTouchedSentinel(t, lastTouchedPath, contents)
result := runLastTouchedProcess(t, binPath, workDir, "show", id, "--json")
assertSuccessfulJSONShow(t, result, id)
gotContents, err := os.ReadFile(lastTouchedPath)
if err != nil {
t.Fatalf("read last-touched after ordinary show: %v", err)
}
if !bytes.Equal(gotContents, contents) {
t.Fatalf("ordinary show last-touched bytes = %q, want %q", gotContents, contents)
}
info, err := os.Stat(lastTouchedPath)
if err != nil {
t.Fatalf("stat last-touched after ordinary show: %v", err)
}
if !info.ModTime().After(mtime) {
t.Fatalf("ordinary show did not advance last-touched mtime: got %v, previous %v", info.ModTime(), mtime)
}
})
}