From a766fafb38e48d2a641de5b1a7f1259220e19da1 Mon Sep 17 00:00:00 2001 From: Benjamin Borbe Date: Wed, 18 Nov 2026 20:52:37 +0100 Subject: [PATCH 1/3] Refuse `--force` on `task complete` and `goal complete` when stdin is not a terminal --- CHANGELOG.md | 4 + integration/cli_test.go | 9 +- pkg/cli/cli.go | 56 +++++- pkg/cli/export_test.go | 6 + pkg/cli/force_tty_test.go | 92 ++++++++++ prompts/completed/284-force-requires-tty.md | 159 ++++++++++++++++++ ...g-parked-exit-requires-registered-watch.md | 3 +- 7 files changed, 315 insertions(+), 14 deletions(-) create mode 100644 pkg/cli/force_tty_test.go create mode 100644 prompts/completed/284-force-requires-tty.md diff --git a/CHANGELOG.md b/CHANGELOG.md index d26734c5..29b6db50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ Please choose versions by [Semantic Versioning](http://semver.org/). * MINOR version when you add functionality in a backwards-compatible manner, and * PATCH version when you make backwards-compatible bug fixes. +## Unreleased + +- fix: refuse `--force` on `task complete` and `goal complete` when stdin is not a terminal, so an agent running without a terminal cannot bypass the closing check with it + ## v0.197.1 - fix: scope ORPHAN_GOAL detection to the goals: block so later frontmatter lists are not reported as missing goals diff --git a/integration/cli_test.go b/integration/cli_test.go index 13beddc4..005f2800 100644 --- a/integration/cli_test.go +++ b/integration/cli_test.go @@ -1987,7 +1987,7 @@ This is my task. cleanup() }) - It("completes with --force despite incomplete subtasks and without close-out fields", func() { + It("refuses --force when stdin is not a terminal and leaves the task unchanged", func() { cmd := exec.Command( binPath, "--config", configPath, @@ -1996,14 +1996,13 @@ This is my task. ) session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) - Eventually(session).Should(gexec.Exit(0)) + Eventually(session).Should(gexec.Exit(1)) + Expect(session.Err).To(gbytes.Say("stdin is not a terminal")) taskPath := filepath.Join(vaultPath, "Tasks", "my-task.md") content, err := os.ReadFile(taskPath) //#nosec G304 -- test file Expect(err).NotTo(HaveOccurred()) - Expect(string(content)).To(ContainSubstring("status: completed")) - Expect(string(content)).NotTo(ContainSubstring("aborted_reason:")) - Expect(string(content)).NotTo(ContainSubstring("gate_successor:")) + Expect(string(content)).To(Equal("---\nstatus: in_progress\n---\n# My Task\n\n- [ ] not done\n")) }) }) }) diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index 45ca4973..dfcc9e42 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -248,6 +248,9 @@ func createCompleteCommand( Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { taskName := args[0] + if err := requireForceFromTerminal(ctx, force); err != nil { + return err + } vaults, err := getVaults(ctx, configLoader, vaultName) if err != nil { return errors.Wrap(ctx, err, "get vaults") @@ -278,14 +281,7 @@ func createCompleteCommand( return result, err } if !OutputFormat(*outputFormat).IsJSON() { - if result.Reason != "" { - fmt.Printf("⚠️ Cannot complete: %s\n", result.Reason) - } else { - fmt.Printf("✅ Task completed: %s\n", result.Name) - } - for _, w := range result.Warnings { - fmt.Printf("⚠️ %s\n", w) - } + printTaskCompleteResult(result) } return result, nil }, @@ -300,6 +296,19 @@ func createCompleteCommand( return cmd } +// printTaskCompleteResult writes the human-readable outcome of a task +// completion. runMutation handles the JSON case, so this is plain mode only. +func printTaskCompleteResult(result ops.MutationResult) { + if result.Reason != "" { + fmt.Printf("⚠️ Cannot complete: %s\n", result.Reason) + return + } + fmt.Printf("✅ Task completed: %s\n", result.Name) + for _, w := range result.Warnings { + fmt.Printf("⚠️ %s\n", w) + } +} + func createDeferCommand( ctx context.Context, configLoader *config.Loader, @@ -534,6 +543,34 @@ func resolveSessionMode(ctx context.Context, mode string) (bool, error) { } } +// requireForceFromTerminal refuses --force when stdin is not a terminal. +// A forced complete overrides the closing check, so it must be confirmable +// by a human at a terminal; an agent piping input, or a process running with +// stdin redirected, must not be able to take the override. +func requireForceFromTerminal(ctx context.Context, force bool) error { + if !force { + return nil + } + interactive, err := resolveSessionMode(ctx, "auto") + if err != nil { + return err + } + return requireTTYForForce(ctx, force, interactive) +} + +// requireTTYForForce returns an error when force is set and isTTY is false. +// It is separate from requireForceFromTerminal so both branches are +// unit-testable without allocating a pty. +func requireTTYForForce(ctx context.Context, force bool, isTTY bool) error { + if !force || isTTY { + return nil + } + return errors.Errorf( + ctx, + "--force requires an interactive terminal: stdin is not a terminal, so the override cannot be confirmed by a human; drop --force or re-run from a terminal", + ) +} + func createTaskListCommand( ctx context.Context, configLoader *config.Loader, @@ -1483,6 +1520,9 @@ func createGoalCompleteCommand( Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { goalName := args[0] + if err := requireForceFromTerminal(ctx, force); err != nil { + return err + } vaults, err := getVaults(ctx, configLoader, vaultName) if err != nil { return errors.Wrap(ctx, err, "get vaults") diff --git a/pkg/cli/export_test.go b/pkg/cli/export_test.go index 5c7d0f0e..9309659c 100644 --- a/pkg/cli/export_test.go +++ b/pkg/cli/export_test.go @@ -57,6 +57,12 @@ func GetWatchVaultsForTest( return getWatchVaults(ctx, configLoader, vaultName) } +// RequireTTYForForceForTest exposes requireTTYForForce with an explicit TTY +// result, so both branches are tested without a pty. +func RequireTTYForForceForTest(ctx context.Context, force bool, isTTY bool) error { + return requireTTYForForce(ctx, force, isTTY) +} + // ParseOpenAnswersForTest exposes parseOpenAnswers for testing, so the flag // grammar is pinned without spawning a binary. func ParseOpenAnswersForTest( diff --git a/pkg/cli/force_tty_test.go b/pkg/cli/force_tty_test.go new file mode 100644 index 00000000..1d4f35e9 --- /dev/null +++ b/pkg/cli/force_tty_test.go @@ -0,0 +1,92 @@ +// Copyright (c) 2026 Benjamin Borbe All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package cli_test + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/spf13/cobra" + + "github.com/bborbe/vault-cli/pkg/cli" +) + +// findSubcommand walks the built command tree to the named top-level command +// and then to the named subcommand. +func findSubcommand(top, sub string) *cobra.Command { + for _, candidate := range cli.NewRootCommand(context.Background()).Commands() { + if candidate.Name() != top { + continue + } + for _, nested := range candidate.Commands() { + if nested.Name() == sub { + return nested + } + } + } + return nil +} + +var _ = Describe("force requires a terminal", func() { + Context("requireTTYForForce", func() { + It("refuses a forced complete when stdin is not a terminal", func() { + err := cli.RequireTTYForForceForTest(context.Background(), true, false) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("stdin is not a terminal")) + }) + + It("accepts a forced complete at a terminal", func() { + Expect(cli.RequireTTYForForceForTest(context.Background(), true, true)). + To(Succeed()) + }) + + It("never gates a non-forced complete", func() { + Expect(cli.RequireTTYForForceForTest(context.Background(), false, false)). + To(Succeed()) + }) + }) + + Context("through cli.Run", func() { + It("refuses task complete --force when stdin is not a terminal", func() { + err := cli.Run(context.Background(), []string{"task", "complete", "Some Task", "--force"}) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("stdin is not a terminal")) + }) + + It("refuses goal complete --force when stdin is not a terminal", func() { + err := cli.Run(context.Background(), []string{"goal", "complete", "Some Goal", "--force"}) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("stdin is not a terminal")) + }) + + It("does not gate a non-forced task complete", func() { + err := cli.Run(context.Background(), []string{"task", "complete", "Some Task"}) + if err != nil { + Expect(err.Error()).NotTo(ContainSubstring("stdin is not a terminal")) + } + }) + }) + + Context("flag surface", func() { + It("does not expose --force on topic complete", func() { + sub := findSubcommand("topic", "complete") + Expect(sub).NotTo(BeNil(), "the root command must expose `topic complete`") + Expect(sub.Flags().Lookup("force")).To(BeNil()) + }) + + It("exposes --force on task complete", func() { + sub := findSubcommand("task", "complete") + Expect(sub).NotTo(BeNil(), "the root command must expose `task complete`") + Expect(sub.Flags().Lookup("force")).NotTo(BeNil()) + }) + + It("exposes --force on goal complete", func() { + sub := findSubcommand("goal", "complete") + Expect(sub).NotTo(BeNil(), "the root command must expose `goal complete`") + Expect(sub.Flags().Lookup("force")).NotTo(BeNil()) + }) + }) +}) diff --git a/prompts/completed/284-force-requires-tty.md b/prompts/completed/284-force-requires-tty.md new file mode 100644 index 00000000..2dac78a6 --- /dev/null +++ b/prompts/completed/284-force-requires-tty.md @@ -0,0 +1,159 @@ +--- +status: completed +summary: Added a terminal-required guard refusing --force on task/goal complete when stdin is not a TTY, with unit and integration coverage, and a CHANGELOG entry +execution_id: vault-cli-force-tty-exec-284-force-requires-tty +dark-factory-version: v0.198.17 +created: "2026-11-18T19:35:00Z" +queued: "2026-11-18T19:44:19Z" +started: "2026-11-18T19:46:55Z" +completed: "2026-11-18T19:52:37Z" +--- + +# Refuse `--force` on `task complete` and `goal complete` when stdin is not a terminal + + +- `--force` on `vault-cli task complete` and `vault-cli goal complete` is refused when stdin is not a terminal: exit 1, a message naming "stdin is not a terminal", and the page left unchanged. +- An operator at a terminal keeps the override: when stdin is a terminal the same command still completes the page. +- The refusal happens before any vault is read or written, so a refused invocation cannot partially mutate a page. +- `vault-cli topic complete` deliberately gains no `--force` flag — it has no close-out gate for the flag to override, and the guard must not ship a placeholder flag. +- A non-forced `complete` is unchanged: it still refuses an open-box page and still lists the open items. +- There is exactly one TTY-detection path (the same one `--mode auto` uses) and no global switch a test could flip. +- The existing integration spec that asserted a forced complete succeeds is replaced by one that asserts the refusal and that the page is left untouched. +- New unit tests cover the refusal, the terminal-accepted path, the unchanged non-forced path, and the absence of `--force` on `topic complete`. +- Ships with a CHANGELOG entry; the full precommit gate stays green. + + + +`vault-cli task complete --force` and `vault-cli goal complete --force` fail with exit code 1 and a message naming "stdin is not a terminal" when stdin is not a TTY, and behave exactly as today when it is a TTY. No other command gains or loses a flag. + + + +Read `CLAUDE.md` for project conventions. Read `docs/development-patterns.md` § Testability and § Naming — dependencies are injected as parameters, never reached through package-level mutable state. + +Read before implementing: +- `pkg/cli/cli.go`: + - `resolveSessionMode(ctx, mode)` (~line 519): the existing stdin-TTY probe. Its `auto` branch does `fd := int(os.Stdin.Fd()) //#nosec G115 ...` then `term.IsTerminal(fd)`. **Reuse this function — do not write a second probe.** The `//#nosec G115` annotation is load-bearing: `gosec` is enabled and only `G104` is excluded, so an unannotated `int(os.Stdin.Fd())` cast fails `make precommit`. + - `createCompleteCommand` (~line 240): declares `var force bool`, registers the flag at the bottom with `cmd.Flags().BoolVar(&force, "force", false, "Complete even if the task has incomplete checkboxes")`, and its `RunE` runs `taskName := args[0]` then `vaults, err := getVaults(...)`. + - `createGoalCompleteCommand` (~line 1472): same shape, flag text "Complete even if open tasks are linked to this goal". + - `createTopicCompleteCommand` (~line 1799): carries a doc comment explaining why it has no `--force`, `--reason` or `--gate-successor`. Leave that command and its comment exactly as they are. + - `Run(ctx, args)` (~line 214) and `Execute()` (~line 3301): `Execute` prints `Error: %v` to stderr and exits 1 when `Run` returns an error. Returning an error from `RunE` is therefore the whole exit-code and stderr contract. +- `pkg/cli/export_test.go`: test-only exports for `package cli_test`, one wrapper per symbol, no state mutation. +- `pkg/cli/task_approve_help_test.go`: the pattern for walking the built command tree (`cli.NewRootCommand(context.Background()).Commands()` then each subcommand's `Commands()`). +- `go.mod`: `golang.org/x/term v0.48.0` is already a direct dependency. + +Why `term.IsTerminal` and not `os.Stdin.Stat()`: `/dev/null` is a character device, so `(stat.Mode() & os.ModeCharDevice) != 0` reports a TTY for `< /dev/null` and the guard would silently do nothing. `term.IsTerminal` issues an `isatty` ioctl and correctly reports false for `/dev/null` and true for a pty. + + + +1. In `pkg/cli/cli.go`, directly after `resolveSessionMode`, add two small functions. Do NOT add a package-level variable — no `var stdinIsTTY`, no setter: + ```go + // requireForceFromTerminal refuses --force when stdin is not a terminal. + // A forced complete overrides the closing check, so it must be confirmable + // by a human at a terminal; an agent piping input, or a process running with + // stdin redirected, must not be able to take the override. + func requireForceFromTerminal(ctx context.Context, force bool) error { + if !force { + return nil + } + interactive, err := resolveSessionMode(ctx, "auto") + if err != nil { + return err + } + return requireTTYForForce(ctx, force, interactive) + } + + // requireTTYForForce returns an error when force is set and isTTY is false. + // It is separate from requireForceFromTerminal so both branches are + // unit-testable without allocating a pty. + func requireTTYForForce(ctx context.Context, force bool, isTTY bool) error { + if !force || isTTY { + return nil + } + return errors.Errorf( + ctx, + "--force requires an interactive terminal: stdin is not a terminal, so the override cannot be confirmed by a human. Drop --force, or re-run from a terminal.", + ) + } + ``` + The message MUST contain the literal substring `stdin is not a terminal` — the unit spec in requirement 5 asserts on it. + +2. In `pkg/cli/cli.go`, call the guard in both `RunE` bodies immediately before `getVaults` (it may follow `taskName := args[0]` / `goalName := args[0]`): + ```go + if err := requireForceFromTerminal(ctx, force); err != nil { + return err + } + ``` + - `createCompleteCommand` (`task complete`) + - `createGoalCompleteCommand` (`goal complete`) + Nothing else in either command changes: same flags, same output, same operation call. + +3. Do NOT add `--force` to `createTopicCompleteCommand`. Its existing doc comment explains why (no close-out gate to override); adding a flag only so it can be refused would ship a placeholder. + +4. In `pkg/cli/export_test.go`, add one wrapper (no state, no setter): + ```go + // RequireTTYForForceForTest exposes requireTTYForForce with an explicit TTY + // result, so both branches are tested without a pty. + func RequireTTYForForceForTest(ctx context.Context, force bool, isTTY bool) error { + return requireTTYForForce(ctx, force, isTTY) + } + ``` + +5. Add `pkg/cli/force_tty_test.go` (package `cli_test`, Ginkgo v2 / Gomega, same license header as the sibling test files). Register no second `RunSpecs` — `cli_suite_test.go` already runs the suite. Cover: + - **the guard itself** — `cli.RequireTTYForForceForTest(context.Background(), true, false)` returns an error whose message contains `stdin is not a terminal`; `(…, true, true)` returns nil; `(…, false, false)` returns nil (a non-forced complete is never gated). + - **`task complete --force` end to end through `cli.Run`** — `err := cli.Run(context.Background(), []string{"task", "complete", "Some Task", "--force"})`. `go test` connects the test binary's stdin to the null device, so the real `resolveSessionMode` probe returns false and the real wiring is exercised. Assert `err` is not nil and `err.Error()` contains `stdin is not a terminal`. + - **`goal complete --force` end to end** — same, for `[]string{"goal", "complete", "Some Goal", "--force"}`. + - **`task complete` without `--force`** — `cli.Run(context.Background(), []string{"task", "complete", "Some Task"})` must NOT return an error containing `stdin is not a terminal`, so the guard never fires on a non-forced complete. + - **`topic complete` exposes no `--force` flag** — walk `cli.NewRootCommand(context.Background())` to `topic` → `complete` and assert `sub.Flags().Lookup("force")` is nil. + - **`task complete` and `goal complete` do expose `--force`** — assert `Flags().Lookup("force")` is not nil on both, so the guard cannot pass by the flag having silently disappeared. + +5b. Update the existing integration spec that this change breaks. `integration/cli_test.go` has `It("completes with --force despite incomplete subtasks and without close-out fields")` (~line 1990) which runs `task complete my-task --force` under `gexec`. `gexec` leaves the child's stdin at the null device, so the new guard makes it exit 1 and `make test` — and therefore `make precommit` — fails. Replace that `It` with a spec asserting the new contract: + ```go + It("refuses --force when stdin is not a terminal and leaves the task unchanged", func() { + cmd := exec.Command( + binPath, + "--config", configPath, + "--vault", "test", + "task", "complete", "my-task", "--force", + ) + session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) + Expect(err).NotTo(HaveOccurred()) + Eventually(session).Should(gexec.Exit(1)) + Expect(session.Err).To(gbytes.Say("stdin is not a terminal")) + + taskPath := filepath.Join(vaultPath, "Tasks", "my-task.md") + content, err := os.ReadFile(taskPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + Expect(string(content)).To(Equal("---\nstatus: in_progress\n---\n# My Task\n\n- [ ] not done\n")) + }) + ``` + `gbytes` and `gexec` are already imported in that file. Do not leave any spec asserting exit 0 for a forced complete with a null-device stdin, and do not add a pty dependency. + +6. Add a `## Unreleased` bullet to `CHANGELOG.md`. Resolve the newest versioned heading at run time and insert `## Unreleased` directly above it; if an `## Unreleased` already exists, append the bullet inside it (never create a second — `grep -c '^## Unreleased$' CHANGELOG.md` must print `1` afterwards). Bullet: + ``` + - fix: refuse `--force` on `task complete` and `goal complete` when stdin is not a terminal, so an agent running without a terminal cannot bypass the closing check with it + ``` + Do NOT bump any version string and do NOT create a tag. + +7. Before finishing, re-run `` and confirm every line passes. + + + +- Do NOT commit — dark-factory handles git. +- Do not add `--force` to any command other than the two named, and do not remove or rename an existing flag. +- Do not introduce a package-level mutable variable or a test-only setter — the TTY result is a parameter. +- Do not write a second stdin-TTY probe; reuse `resolveSessionMode`. +- Do not change `pkg/ops` — the guard is a CLI-layer concern about the process's stdin, and `pkg/ops` must keep returning structured results without touching stdout/stderr. +- Do not change what a non-forced `complete` does, and do not change any refusal message it already prints. +- Error handling: `github.com/bborbe/errors` with `ctx`; never `fmt.Errorf`. +- Tests: Ginkgo v2 / Gomega only; never allocate a pty in a unit test (the pty path is verified on the installed binary, not here). + + + +- `make precommit` → exit 0. +- `grep -c 'stdin is not a terminal' pkg/cli/cli.go` → at least 1. +- `grep -c 'requireForceFromTerminal(ctx, force)' pkg/cli/cli.go` → exactly 2. +- `grep -c 'BoolVar(&force, "force"' pkg/cli/cli.go` → exactly 3: the two `complete` commands plus the pre-existing `task set --force` phase-regression flag, which is out of scope and must be left untouched. Any other count means a flag was added or removed. +- `grep -rn 'var stdinIsTTY' pkg/cli/ | wc -l` → 0. +- `go build ./...` → exit 0. +- `go test ./pkg/cli/... ./integration/...` → green, including the new specs and the rewritten integration spec. + diff --git a/specs/in-progress/067-bug-parked-exit-requires-registered-watch.md b/specs/in-progress/067-bug-parked-exit-requires-registered-watch.md index 1060ba94..907d671e 100644 --- a/specs/in-progress/067-bug-parked-exit-requires-registered-watch.md +++ b/specs/in-progress/067-bug-parked-exit-requires-registered-watch.md @@ -1,6 +1,7 @@ --- -status: approved +status: verifying approved: "2026-11-15T13:23:19Z" +verifying: "2026-11-18T19:44:21Z" branch: dark-factory/bug-parked-exit-requires-registered-watch --- From ec68167a79f76dfec83d551924cbf3d580235c98 Mon Sep 17 00:00:00 2001 From: Benjamin Borbe Date: Wed, 18 Nov 2026 20:52:38 +0100 Subject: [PATCH 2/3] move prompt to completed --- prompts/completed/283-lint-orphan-goal-block-scope.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/prompts/completed/283-lint-orphan-goal-block-scope.md b/prompts/completed/283-lint-orphan-goal-block-scope.md index c784e122..e960de32 100644 --- a/prompts/completed/283-lint-orphan-goal-block-scope.md +++ b/prompts/completed/283-lint-orphan-goal-block-scope.md @@ -1,12 +1,12 @@ --- -status: committing +status: completed summary: 'Scoped ORPHAN_GOAL detection to the goals: block with line-bounded regexes, unescaped YAML single-quote doubling in goal names, added four regression contexts, and a CHANGELOG entry.' execution_id: vault-cli-orphan-goal-exec-283-lint-orphan-goal-block-scope dark-factory-version: v0.199.1 created: "2026-11-17T18:45:00Z" queued: "2026-11-17T18:18:01Z" started: "2026-11-17T20:44:20Z" -completed: "2026-11-17T20:58:11Z" +completed: "2026-11-18T19:52:38Z" --- # Scope ORPHAN_GOAL detection to the `goals:` block From ea4c87cdf8d7c901e9d488d0f2c723f69933d6d6 Mon Sep 17 00:00:00 2001 From: Benjamin Borbe Date: Wed, 18 Nov 2026 22:19:26 +0100 Subject: [PATCH 3/3] Restore warnings on the refusal path and harden the force-guard tests --- CHANGELOG.md | 2 +- pkg/cli/cli.go | 19 +-- pkg/cli/export_test.go | 8 ++ pkg/cli/force_tty_test.go | 30 ++++- .../completed/285-force-tty-review-fixes.md | 117 ++++++++++++++++++ 5 files changed, 164 insertions(+), 12 deletions(-) create mode 100644 prompts/completed/285-force-tty-review-fixes.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 29b6db50..9517ba39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Please choose versions by [Semantic Versioning](http://semver.org/). ## Unreleased -- fix: refuse `--force` on `task complete` and `goal complete` when stdin is not a terminal, so an agent running without a terminal cannot bypass the closing check with it +- fix: refuse `--force` on `task complete` and `goal complete` when stdin is not a terminal, so an agent running without a terminal cannot bypass the closing check with it; the extracted task-complete helper now prints warnings in both branches and wraps the session-mode error ## v0.197.1 diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index dfcc9e42..66940696 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -8,6 +8,7 @@ import ( "context" "encoding/json" "fmt" + "io" "log/slog" "os" "path/filepath" @@ -281,7 +282,7 @@ func createCompleteCommand( return result, err } if !OutputFormat(*outputFormat).IsJSON() { - printTaskCompleteResult(result) + printTaskCompleteResult(os.Stdout, result) } return result, nil }, @@ -298,14 +299,16 @@ func createCompleteCommand( // printTaskCompleteResult writes the human-readable outcome of a task // completion. runMutation handles the JSON case, so this is plain mode only. -func printTaskCompleteResult(result ops.MutationResult) { +// Warnings print in both the refusal and the success branch: the refusal +// branch used to return early and drop them. +func printTaskCompleteResult(w io.Writer, result ops.MutationResult) { if result.Reason != "" { - fmt.Printf("⚠️ Cannot complete: %s\n", result.Reason) - return + fmt.Fprintf(w, "⚠️ Cannot complete: %s\n", result.Reason) + } else { + fmt.Fprintf(w, "✅ Task completed: %s\n", result.Name) } - fmt.Printf("✅ Task completed: %s\n", result.Name) - for _, w := range result.Warnings { - fmt.Printf("⚠️ %s\n", w) + for _, warning := range result.Warnings { + fmt.Fprintf(w, "⚠️ %s\n", warning) } } @@ -553,7 +556,7 @@ func requireForceFromTerminal(ctx context.Context, force bool) error { } interactive, err := resolveSessionMode(ctx, "auto") if err != nil { - return err + return errors.Wrap(ctx, err, "resolve session mode") } return requireTTYForForce(ctx, force, interactive) } diff --git a/pkg/cli/export_test.go b/pkg/cli/export_test.go index 9309659c..34ecc311 100644 --- a/pkg/cli/export_test.go +++ b/pkg/cli/export_test.go @@ -6,6 +6,7 @@ package cli import ( "context" + "io" "github.com/spf13/cobra" @@ -48,6 +49,13 @@ func FormatRollupWeeklyPlainForTest(result ops.RollupWeeklyResult) string { return formatRollupWeeklyPlain(result) } +// PrintTaskCompleteResultForTest exposes printTaskCompleteResult with an +// explicit writer, so both output branches are testable without swapping +// os.Stdout. +func PrintTaskCompleteResultForTest(w io.Writer, result ops.MutationResult) { + printTaskCompleteResult(w, result) +} + // GetWatchVaultsForTest exposes getWatchVaults for testing. func GetWatchVaultsForTest( ctx context.Context, diff --git a/pkg/cli/force_tty_test.go b/pkg/cli/force_tty_test.go index 1d4f35e9..f3a7718e 100644 --- a/pkg/cli/force_tty_test.go +++ b/pkg/cli/force_tty_test.go @@ -5,6 +5,7 @@ package cli_test import ( + "bytes" "context" . "github.com/onsi/ginkgo/v2" @@ -12,6 +13,7 @@ import ( "github.com/spf13/cobra" "github.com/bborbe/vault-cli/pkg/cli" + "github.com/bborbe/vault-cli/pkg/ops" ) // findSubcommand walks the built command tree to the named top-level command @@ -64,9 +66,31 @@ var _ = Describe("force requires a terminal", func() { It("does not gate a non-forced task complete", func() { err := cli.Run(context.Background(), []string{"task", "complete", "Some Task"}) - if err != nil { - Expect(err.Error()).NotTo(ContainSubstring("stdin is not a terminal")) - } + Expect(err).To(HaveOccurred(), "no task store is reachable, so this must fail before any TTY gate") + Expect(err.Error()).NotTo(ContainSubstring("stdin is not a terminal")) + }) + }) + + Context("printTaskCompleteResult", func() { + It("prints warnings in the refusal branch", func() { + var buf bytes.Buffer + cli.PrintTaskCompleteResultForTest(&buf, ops.MutationResult{ + Reason: "3 subtasks are incomplete", + Warnings: []string{"first warning", "second warning"}, + }) + Expect(buf.String()).To(ContainSubstring("Cannot complete: 3 subtasks are incomplete")) + Expect(buf.String()).To(ContainSubstring("first warning")) + Expect(buf.String()).To(ContainSubstring("second warning")) + }) + + It("prints warnings in the success branch", func() { + var buf bytes.Buffer + cli.PrintTaskCompleteResultForTest(&buf, ops.MutationResult{ + Name: "Some Task", + Warnings: []string{"a warning"}, + }) + Expect(buf.String()).To(ContainSubstring("Task completed: Some Task")) + Expect(buf.String()).To(ContainSubstring("a warning")) }) }) diff --git a/prompts/completed/285-force-tty-review-fixes.md b/prompts/completed/285-force-tty-review-fixes.md new file mode 100644 index 00000000..991736cd --- /dev/null +++ b/prompts/completed/285-force-tty-review-fixes.md @@ -0,0 +1,117 @@ +--- +status: completed +summary: Restored both-branch warning printing in printTaskCompleteResult with an injectable writer, wrapped the session-mode error, made the non-forced TTY test assert unconditionally, and extended the existing Unreleased changelog bullet +execution_id: vault-cli-force-tty-exec-285-force-tty-review-fixes +dark-factory-version: v0.198.17 +created: "2026-11-18T21:05:00Z" +queued: "2026-11-18T21:11:51Z" +started: "2026-11-18T21:15:03Z" +completed: "2026-11-18T21:19:26Z" +--- + +# Restore warnings on the refusal path and harden the force-guard tests + + +- The task-complete helper again prints warnings in both branches, as the inline code it replaced did — the refusal branch is unreachable today, so this is behaviour preservation, not a user-visible fix. +- The new guard no longer contains a bare `return err`; the error from the session-mode probe is wrapped like every other error in the package. +- The non-forced `complete` test asserts unconditionally instead of only when an error happens to be returned, so a silently broken command path can no longer pass it. +- No behaviour change to the TTY guard itself: a forced complete still refuses off a terminal and still proceeds at one. +- `make precommit` passes. + + + +`printTaskCompleteResult` prints `result.Warnings` in both the refusal and the success branch exactly as the inline code did before the extraction, and the two test/error-handling gaps the review found are closed, with no other behavioural change. + + + +Read `CLAUDE.md` for project conventions. Read `docs/development-patterns.md`. + +Error wrapping: `go-error-wrapping-guide.md` (coding plugin docs) — `errors.Wrap(ctx, err, msg)`, never a bare `return err` in new code. + +Read before implementing: +- `pkg/cli/cli.go`: + - `createCompleteCommand` (~line 240): its `RunE` calls `printTaskCompleteResult(result)` in the non-JSON branch. + - `printTaskCompleteResult` (~line 299): the helper added by the previous commit. It currently `return`s after printing the refusal reason, so `result.Warnings` is skipped whenever `result.Reason != ""`. + - `requireForceFromTerminal` (~line 546): calls `resolveSessionMode(ctx, "auto")` and currently does a bare `return err` on the impossible error branch. + - `resolveSessionMode` (~line 519): its `auto` branch returns `(term.IsTerminal(fd), nil)` and can never error. +- `pkg/cli/force_tty_test.go`: the specs added by the previous commit; the non-forced case is written as `if err != nil { Expect(...) }`. +- `pkg/ops/complete.go` (~line 234): `checkSubtaskCompletion` is the only producer of a non-empty `Result.Reason`. It sets no `Warnings` today, so the dropped-warnings path is latent — fix it anyway: the extraction claimed to be behaviour-preserving and is not. + +Before this commit the inline code printed the warnings in BOTH branches: +```go +if result.Reason != "" { + fmt.Printf("⚠️ Cannot complete: %s\n", result.Reason) +} else { + fmt.Printf("✅ Task completed: %s\n", result.Name) +} +for _, w := range result.Warnings { + fmt.Printf("⚠️ %s\n", w) +} +``` + + + +1. In `pkg/cli/cli.go`, restore both-branch warning printing in `printTaskCompleteResult`, and take the destination writer as a parameter so the output is testable without capturing `os.Stdout`: + ```go + // printTaskCompleteResult writes the human-readable outcome of a task + // completion. runMutation handles the JSON case, so this is plain mode only. + // Warnings print in both the refusal and the success branch: the refusal + // branch used to return early and drop them. + func printTaskCompleteResult(w io.Writer, result ops.MutationResult) { + if result.Reason != "" { + fmt.Fprintf(w, "⚠️ Cannot complete: %s\n", result.Reason) + } else { + fmt.Fprintf(w, "✅ Task completed: %s\n", result.Name) + } + for _, warning := range result.Warnings { + fmt.Fprintf(w, "⚠️ %s\n", warning) + } + } + ``` + Update its one call site in `createCompleteCommand`'s `RunE` to `printTaskCompleteResult(os.Stdout, result)`, and add `io` to the imports. + + Then add a `PrintTaskCompleteResultForTest(w io.Writer, result ops.MutationResult)` hook in `pkg/cli/export_test.go` (matching the existing `FormatRollupWeeklyPlainForTest` pattern) and a spec in `pkg/cli/force_tty_test.go` that writes into a `bytes.Buffer` with both `Reason` and `Warnings` set and asserts the buffer contains both — so the changed behaviour is covered even though the production refusal branch is unreachable. Never swap `os.Stdout` in the test. + +2. In `pkg/cli/cli.go`, replace the bare `return err` in `requireForceFromTerminal` with a wrapped error, matching `go-error-wrapping-guide.md` ("never bare `return err`"): + ```go + interactive, err := resolveSessionMode(ctx, "auto") + if err != nil { + return errors.Wrap(ctx, err, "resolve session mode") + } + ``` + +3. In `pkg/cli/force_tty_test.go`, make the non-forced spec assert unconditionally. With no config file the loader falls back to a default vault at `$HOME/Documents/vault` (`getDefaultConfig`), so `cli.Run` fails on the task lookup rather than on config; the assertion that matters is that the error is not the TTY refusal: + ```go + It("does not gate a non-forced task complete", func() { + err := cli.Run(context.Background(), []string{"task", "complete", "Some Task"}) + Expect(err).To(HaveOccurred(), "no task store is reachable, so this must fail before any TTY gate") + Expect(err.Error()).NotTo(ContainSubstring("stdin is not a terminal")) + }) + ``` + Keep every other spec in that file unchanged. + +4. Extend the existing `## Unreleased` bullet in `CHANGELOG.md` rather than adding a new one — this branch has not been released, so a fresh `- fix:` line would record a fix to code that never shipped. Append to the end of the existing bullet: + ``` + ; the extracted task-complete helper now prints warnings in both branches and wraps the session-mode error + ``` + Do not create a second `## Unreleased` heading; `grep -c '^## Unreleased$' CHANGELOG.md` must print `1` afterwards. + +5. Before finishing, re-run `` and confirm every line passes. + + + +- Do NOT commit — dark-factory handles git. +- Do not change the TTY guard's behaviour, its message text, its placement, or which commands carry `--force`. +- Do not touch `commands/complete-task.md` or `commands/complete-goal.md` — out of scope for this branch. +- Do not revert or edit `specs/` or `prompts/` record files. +- Error handling: `github.com/bborbe/errors` with `ctx`; never `fmt.Errorf`, never a bare `return err`. +- Tests: Ginkgo v2 / Gomega only. + + + +- `make precommit` → exit 0. +- `grep -c '^## Unreleased$' CHANGELOG.md` → exactly 1. +- `grep -A9 'func printTaskCompleteResult' pkg/cli/cli.go | grep -cE '^[[:space:]]*return$'` → 0 and `grep -A9 'func printTaskCompleteResult' pkg/cli/cli.go | grep -c 'range result.Warnings'` → 1 (the early return is gone AND the warnings loop is still present, so neither the unfixed code nor a fix that deletes the loop passes). +- `grep -A8 'func requireForceFromTerminal' pkg/cli/cli.go | grep -c 'return err$'` → 0 (the window covers the whole function so an inserted line cannot shift the bare return out of range; the file's other bare `return err` sites are pre-existing and out of scope). +- `go test ./pkg/cli/...` → green. +