fix(update,close): gate the no-ID last-touched fallback to interactive sessions (bd-m00pb) (#4839)
* fix(update,close): gate the no-ID last-touched fallback to interactive sessions (bd-m00pb) bd update/close with no issue ID fall back to the last-touched issue. Convenient at a prompt, but in scripts it turns an empty variable into a mutation of whatever issue happened to be touched last: in a real agent session (wyvern wy-c9uoz, forensics wy-yuclk), a failed 'bd create --silent' printed nothing and the follow-on 'bd update $ID ...' silently rewrote an unrelated CLOSED bead's assignee/status/close_reason. The fallback now applies only when stdin is a terminal, with explicit overrides mirroring the isNonInteractiveBootstrap precedence: BD_LAST_TOUCHED_FALLBACK=1/true always allows, =0/false always denies, then BD_NON_INTERACTIVE / CI deny, then TTY detection. Read-only consumers (bd show --current) are unchanged, and the proxied-server paths already hard-errored on a missing ID. The non-interactive refusal names the opt-in env var so scripted callers that relied on the fallback get a one-line migration. CLI reference pages regenerated; this also picks up one pre-existing generated-drift hunk from the auto-backup help text (5f685959c). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(changelog): entry for the last-touched fallback guard (bd-m00pb, #4839) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(update,close): refuse a missing ID in Args validation, before pre-run side effects (bd-m00pb) Review response for #4839 (maphew, 2026-07-24): - Rebased onto main (647 commits); the update.go long-help now carries both the multi-ID partial-failure contract (b2b153b7b) and the fallback gating. - The non-interactive no-ID refusal moves from RunE to cobra argument validation, which runs before PersistentPreRunE — so a scripted call with an empty $ID fails fast with the advertised message instead of first running autoMigrateOnVersionBump, opening the store, or auto-importing JSONL. New guard subtest proves it: outside any workspace the refusal message appears and the directory stays untouched. - Dropped the regenerated docs/cli-reference hunks and the unrelated backup hunk per the docs/cli-docs.pin release-pin policy; source help + changelog only. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
4e8b017fd4
commit
23b2a7e784
6 changed files with 275 additions and 6 deletions
13
CHANGELOG.md
13
CHANGELOG.md
|
|
@ -50,6 +50,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
note: in server mode that was behaving like `on`; it now genuinely stops
|
||||
minting version commits until an explicit `bd dolt commit`.
|
||||
|
||||
- **The no-ID "last touched issue" fallback on `bd update` / `bd close` is
|
||||
now interactive-only** (bd-m00pb,
|
||||
[#4839](https://github.com/gastownhall/beads/pull/4839)).
|
||||
Previously a scripted `bd update $ID ...` with an accidentally empty `$ID`
|
||||
silently mutated whatever issue was touched last — a real agent session
|
||||
corrupted an unrelated closed bead this way. The missing-ID refusal happens
|
||||
in argument validation, before any store open, migration, or auto-import
|
||||
side effect. The fallback now requires stdin to be a terminal;
|
||||
`BD_NON_INTERACTIVE=1` and `CI=1/true` also disable it. Scripts that
|
||||
intentionally relied on it can set `BD_LAST_TOUCHED_FALLBACK=1` (or `=0` to
|
||||
disable the fallback everywhere). Explicit IDs and `bd show --current` are
|
||||
unaffected.
|
||||
|
||||
|
||||
- **`bd delete --cascade` no longer marks LIVE issues as deleted in other
|
||||
issues' text** (bd-x82so). When the deletion named a wisp, the set used to
|
||||
|
|
|
|||
|
|
@ -27,13 +27,25 @@ var closeCmd = &cobra.Command{
|
|||
Long: `Close one or more issues.
|
||||
|
||||
If no issue ID is provided, closes the last touched issue (from most recent
|
||||
create, update, show, or close operation).
|
||||
create, update, show, or close operation). This fallback only applies in
|
||||
interactive sessions (stdin is a terminal); in scripts and agent sessions a
|
||||
missing ID is an error, so a command built from an empty variable cannot
|
||||
silently close an unrelated issue. Set BD_LAST_TOUCHED_FALLBACK=1 to allow
|
||||
the fallback anywhere, or =0 to disable it entirely.
|
||||
|
||||
When closing multiple issues, provide one --reason for all IDs or repeat
|
||||
--reason once per ID. Reasons map positionally: the first --reason applies
|
||||
to the first ID, the second --reason to the second ID, regardless of where
|
||||
the flags appear in the command line.`,
|
||||
Args: cobra.MinimumNArgs(0),
|
||||
// Refuse a missing ID in argument validation, before root's
|
||||
// PersistentPreRunE can open the store, migrate, or auto-import
|
||||
// (bd-m00pb); see updateCmd for the full rationale.
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 && !AllowLastTouchedFallback() {
|
||||
return HandleErrorRespectJSON("no issue ID provided (the last-touched fallback only applies in interactive sessions; pass an explicit issue ID or set BD_LAST_TOUCHED_FALLBACK=1)")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
|
|
@ -50,7 +62,8 @@ the flags appear in the command line.`,
|
|||
return runCloseProxiedServer(cmd, rootCtx, args)
|
||||
}
|
||||
|
||||
// If no IDs provided, use last touched issue
|
||||
// If no IDs provided, use last touched issue (interactive only;
|
||||
// the non-interactive case was already refused in Args validation)
|
||||
if len(args) == 0 {
|
||||
lastTouched := GetLastTouchedID()
|
||||
if lastTouched == "" {
|
||||
|
|
|
|||
|
|
@ -6,11 +6,42 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
)
|
||||
|
||||
const lastTouchedFile = "last-touched"
|
||||
|
||||
// lastTouchedFallbackEnv overrides the no-ID "last touched issue" fallback
|
||||
// on mutating commands: 1/true always allows it, 0/false always denies it.
|
||||
const lastTouchedFallbackEnv = "BD_LAST_TOUCHED_FALLBACK"
|
||||
|
||||
// AllowLastTouchedFallback reports whether a mutating command (update,
|
||||
// close) may substitute the last-touched issue when no ID was given.
|
||||
//
|
||||
// The fallback is convenient at an interactive prompt but dangerous in
|
||||
// scripts: `bd update "$ID" ...` with an accidentally empty $ID silently
|
||||
// mutates whatever issue happened to be touched last (bd-m00pb; a real
|
||||
// agent session corrupted an unrelated closed issue this way). Read-only
|
||||
// consumers like `bd show --current` are unaffected.
|
||||
//
|
||||
// Precedence mirrors isNonInteractiveBootstrap:
|
||||
// BD_LAST_TOUCHED_FALLBACK (any explicit value wins, only 1/true enables) >
|
||||
// BD_NON_INTERACTIVE / CI (deny) > stdin terminal detection.
|
||||
func AllowLastTouchedFallback() bool {
|
||||
if v := os.Getenv(lastTouchedFallbackEnv); v != "" {
|
||||
return v == "1" || v == "true"
|
||||
}
|
||||
if v := os.Getenv("BD_NON_INTERACTIVE"); v == "1" || v == "true" {
|
||||
return false
|
||||
}
|
||||
if v := os.Getenv("CI"); v == "1" || v == "true" {
|
||||
return false
|
||||
}
|
||||
return term.IsTerminal(int(os.Stdin.Fd()))
|
||||
}
|
||||
|
||||
// GetLastTouchedID returns the ID of the last touched issue.
|
||||
// Returns empty string if no last touched issue exists or the file is unreadable.
|
||||
func GetLastTouchedID() string {
|
||||
|
|
|
|||
148
cmd/bd/last_touched_guard_test.go
Normal file
148
cmd/bd/last_touched_guard_test.go
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// runBDWithEnv runs the bd binary with args in workDir plus extraEnv and
|
||||
// returns exit code and combined output. Unlike runBDStdout it does not
|
||||
// fail the test on a non-zero exit — guard tests assert on refusals.
|
||||
func runBDWithEnv(t *testing.T, binPath, workDir string, extraEnv []string, args ...string) (int, string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, binPath, args...)
|
||||
cmd.Dir = workDir
|
||||
cmd.Env = append(os.Environ(),
|
||||
"HOME="+t.TempDir(),
|
||||
"XDG_CONFIG_HOME="+t.TempDir(),
|
||||
"BEADS_TEST_IGNORE_REPO_CONFIG=1",
|
||||
"BEADS_DIR=",
|
||||
"BEADS_DB=",
|
||||
"LINEAR_API_KEY=",
|
||||
// Neutralize CI/agent env so each case controls the guard inputs.
|
||||
"CI=",
|
||||
"BD_NON_INTERACTIVE=",
|
||||
"BD_LAST_TOUCHED_FALLBACK=",
|
||||
)
|
||||
cmd.Env = append(cmd.Env, extraEnv...)
|
||||
var buf bytes.Buffer
|
||||
cmd.Stdout = &buf
|
||||
cmd.Stderr = &buf
|
||||
err := cmd.Run()
|
||||
code := 0
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
code = exitErr.ExitCode()
|
||||
} else {
|
||||
t.Fatalf("bd %v in %s: %v\noutput: %s", args, workDir, err, buf.String())
|
||||
}
|
||||
}
|
||||
return code, buf.String()
|
||||
}
|
||||
|
||||
// TestNoIDFallbackGuard verifies the last-touched fallback on mutating
|
||||
// commands is refused in non-interactive sessions and honored only with an
|
||||
// explicit BD_LAST_TOUCHED_FALLBACK=1 opt-in (bd-m00pb). The bd subprocess
|
||||
// runs without a TTY on stdin, which is exactly the incident scenario: a
|
||||
// scripted `bd update $ID ...` where $ID expanded to nothing.
|
||||
func TestNoIDFallbackGuard(t *testing.T) {
|
||||
binPath := buildBDUnderTest(t)
|
||||
workDir := t.TempDir()
|
||||
initBeadsWorkspace(t, binPath, workDir)
|
||||
|
||||
id := runBDStdout(t, binPath, workDir, "q", "Guard test issue")
|
||||
if id == "" {
|
||||
t.Fatal("bd q returned empty issue ID")
|
||||
}
|
||||
|
||||
t.Run("update without ID refused non-interactively", func(t *testing.T) {
|
||||
code, out := runBDWithEnv(t, binPath, workDir, nil, "update", "--priority", "3")
|
||||
if code == 0 {
|
||||
t.Fatalf("bd update with no ID succeeded non-interactively; output: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "BD_LAST_TOUCHED_FALLBACK") {
|
||||
t.Errorf("refusal should mention the opt-in env var; output: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close without ID refused non-interactively", func(t *testing.T) {
|
||||
code, out := runBDWithEnv(t, binPath, workDir, nil, "close")
|
||||
if code == 0 {
|
||||
t.Fatalf("bd close with no ID succeeded non-interactively; output: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "BD_LAST_TOUCHED_FALLBACK") {
|
||||
t.Errorf("refusal should mention the opt-in env var; output: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("BD_NON_INTERACTIVE=1 also refuses", func(t *testing.T) {
|
||||
code, out := runBDWithEnv(t, binPath, workDir,
|
||||
[]string{"BD_NON_INTERACTIVE=1"}, "update", "--priority", "3")
|
||||
if code == 0 {
|
||||
t.Fatalf("bd update with no ID succeeded under BD_NON_INTERACTIVE=1; output: %s", out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit opt-in restores the fallback", func(t *testing.T) {
|
||||
// Seed the marker directly: `bd q` does not record last-touched
|
||||
// (only create/update/show/close do), and the subtest should not
|
||||
// depend on which earlier command happened to write it.
|
||||
lastTouchedPath := filepath.Join(workDir, ".beads", lastTouchedFile)
|
||||
if err := os.WriteFile(lastTouchedPath, []byte(id+"\n"), 0600); err != nil {
|
||||
t.Fatalf("seed last-touched: %v", err)
|
||||
}
|
||||
code, out := runBDWithEnv(t, binPath, workDir,
|
||||
[]string{"BD_LAST_TOUCHED_FALLBACK=1"}, "update", "--priority", "1")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd update with opt-in failed (exit %d): %s", code, out)
|
||||
}
|
||||
if !strings.Contains(out, id) {
|
||||
t.Errorf("opt-in fallback should have updated last-touched issue %s; output: %s", id, out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("refusal fires before store open", func(t *testing.T) {
|
||||
// A bare directory that is not a beads workspace: if the no-ID
|
||||
// refusal ran after root's pre-run hooks, this would die on a
|
||||
// store/workspace error (or, in a real workspace, run a migration
|
||||
// or JSONL auto-import first). Argument validation runs before
|
||||
// PersistentPreRunE, so the advertised message must appear and the
|
||||
// directory must stay untouched.
|
||||
bareDir := t.TempDir()
|
||||
code, out := runBDWithEnv(t, binPath, bareDir, nil, "update", "--priority", "3")
|
||||
if code == 0 {
|
||||
t.Fatalf("bd update with no ID succeeded outside a workspace; output: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "BD_LAST_TOUCHED_FALLBACK") {
|
||||
t.Errorf("refusal should fail fast with the advertised message, not a store error; output: %s", out)
|
||||
}
|
||||
entries, err := os.ReadDir(bareDir)
|
||||
if err != nil {
|
||||
t.Fatalf("read bare dir: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
t.Errorf("no-ID refusal must have no side effects; created: %v", names)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit ID always works", func(t *testing.T) {
|
||||
code, out := runBDWithEnv(t, binPath, workDir, nil, "update", id, "--priority", "2")
|
||||
if code != 0 {
|
||||
t.Fatalf("bd update with explicit ID failed (exit %d): %s", code, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -5,6 +5,8 @@ import (
|
|||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func TestLastTouchedBasic(t *testing.T) {
|
||||
|
|
@ -110,6 +112,53 @@ func TestSetLastTouchedIDAdvancesMtime(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestAllowLastTouchedFallback_EnvPrecedence covers the env-driven branches
|
||||
// of the guard (bd-m00pb). The trailing stdin-TTY branch is exercised by the
|
||||
// default-deny case below and end-to-end in last_touched_guard_test.go.
|
||||
func TestAllowLastTouchedFallback_EnvPrecedence(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
fallbackEnv string
|
||||
nonInteractive string
|
||||
ci string
|
||||
want bool
|
||||
}{
|
||||
{"explicit 1 wins over non-interactive", "1", "1", "true", true},
|
||||
{"explicit true wins over CI", "true", "", "true", true},
|
||||
{"explicit 0 denies", "0", "", "", false},
|
||||
{"explicit false denies", "false", "", "", false},
|
||||
{"garbage value denies", "yes", "", "", false},
|
||||
{"BD_NON_INTERACTIVE=1 denies", "", "1", "", false},
|
||||
{"BD_NON_INTERACTIVE=true denies", "", "true", "", false},
|
||||
{"CI=true denies", "", "", "true", false},
|
||||
{"CI=1 denies", "", "", "1", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv(lastTouchedFallbackEnv, tc.fallbackEnv)
|
||||
t.Setenv("BD_NON_INTERACTIVE", tc.nonInteractive)
|
||||
t.Setenv("CI", tc.ci)
|
||||
if got := AllowLastTouchedFallback(); got != tc.want {
|
||||
t.Errorf("AllowLastTouchedFallback() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAllowLastTouchedFallback_DefaultDeniesNonTTY verifies the default
|
||||
// path denies when stdin is not a terminal and no env override is set.
|
||||
func TestAllowLastTouchedFallback_DefaultDeniesNonTTY(t *testing.T) {
|
||||
t.Setenv(lastTouchedFallbackEnv, "")
|
||||
t.Setenv("BD_NON_INTERACTIVE", "")
|
||||
t.Setenv("CI", "")
|
||||
if term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
t.Skip("stdin is a terminal; default-deny branch not observable")
|
||||
}
|
||||
if AllowLastTouchedFallback() {
|
||||
t.Error("AllowLastTouchedFallback() = true with non-TTY stdin and no override, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetLastTouchedIDIgnoresEmpty(t *testing.T) {
|
||||
// Create a temp directory
|
||||
tmpDir := t.TempDir()
|
||||
|
|
|
|||
|
|
@ -71,7 +71,11 @@ var updateCmd = &cobra.Command{
|
|||
Long: `Update one or more issues.
|
||||
|
||||
If no issue ID is provided, updates the last touched issue (from most recent
|
||||
create, update, show, or close operation).
|
||||
create, update, show, or close operation). This fallback only applies in
|
||||
interactive sessions (stdin is a terminal); in scripts and agent sessions a
|
||||
missing ID is an error, so a command built from an empty variable cannot
|
||||
silently mutate an unrelated issue. Set BD_LAST_TOUCHED_FALLBACK=1 to allow
|
||||
the fallback anywhere, or =0 to disable it entirely.
|
||||
|
||||
Updates are applied per issue ID, not atomically across IDs: when some IDs
|
||||
fail, the remaining issues are still updated, every failed ID is reported on
|
||||
|
|
@ -81,7 +85,17 @@ Exit codes: 1 for general failures; 13 when every failure is a stale
|
|||
--if-assignee/--if-status guard (the precondition no longer held, nothing was
|
||||
written — another actor won the race, so retrying the same guard is
|
||||
pointless).`,
|
||||
Args: cobra.MinimumNArgs(0),
|
||||
// The non-interactive no-ID refusal lives in argument validation, which
|
||||
// cobra runs before root's PersistentPreRunE — so a scripted `bd update
|
||||
// $ID ...` with an empty $ID fails fast, before the pre-run hooks can
|
||||
// open the store, run a version-bump migration, or auto-import JSONL
|
||||
// (bd-m00pb). The interactive fallback itself is resolved in RunE.
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 && !AllowLastTouchedFallback() {
|
||||
return HandleErrorRespectJSON("no issue ID provided (the last-touched fallback only applies in interactive sessions; pass an explicit issue ID or set BD_LAST_TOUCHED_FALLBACK=1)")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
|
|
@ -98,7 +112,8 @@ pointless).`,
|
|||
return runUpdateProxiedServer(cmd, rootCtx, args)
|
||||
}
|
||||
|
||||
// If no IDs provided, use last touched issue
|
||||
// If no IDs provided, use last touched issue (interactive only;
|
||||
// the non-interactive case was already refused in Args validation)
|
||||
if len(args) == 0 {
|
||||
lastTouched := GetLastTouchedID()
|
||||
if lastTouched == "" {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue