diff --git a/CHANGELOG.md b/CHANGELOG.md index ee21395..4e2a526 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: `goal complete` and `topic complete` refuse to close a page whose own closure evidence is incomplete, name every open item on stdout and in `--output json` under `open_items`, and treat an already-completed or aborted page as a no-op instead of an error + ## v0.198.1 - 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 diff --git a/integration/cli_test.go b/integration/cli_test.go index 9327b77..c85991d 100644 --- a/integration/cli_test.go +++ b/integration/cli_test.go @@ -2077,7 +2077,8 @@ This is my task. vaultPath, configPath, cleanup = createTempVaultWithGoals( map[string]string{}, map[string]string{ - "my-goal": "---\nstatus: in_progress\n---\n# My Goal\n", + "my-goal": "---\nstatus: in_progress\n---\n# My Goal\n" + + "# Success Criteria\n- [x] done\n", }, ) }) @@ -2193,7 +2194,8 @@ This is my task. vaultPath, configPath, cleanup = createTempVaultWithGoals( map[string]string{}, map[string]string{ - "my-goal": "---\nstatus: in_progress\nphase: execution\n---\n# My Goal\n", + "my-goal": "---\nstatus: in_progress\nphase: execution\n---\n# My Goal\n" + + "# Success Criteria\n- [x] done\n", }, ) }) @@ -2290,6 +2292,501 @@ This is my task. }) }) + Describe("vault-cli goal and topic closure gate", func() { + It("goal complete refuses an open Success Criteria box and leaves status in_progress", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{}, + map[string]string{ + "my-goal": "---\nstatus: in_progress\n---\n# Success Criteria\n" + + "- [ ] an open criterion\n# Definition of Done\n- [x] done\n", + }, + ) + defer cleanup() + + goalPath := filepath.Join(vaultPath, "Goals", "my-goal.md") + readFile := func() string { + content, err := os.ReadFile(goalPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + return string(content) + } + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("goal", "complete", "my-goal") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("an open criterion")) + Expect(readFile()).To(ContainSubstring("status: in_progress")) + }) + + It("goal complete closes a fully ticked goal with terminal linked tasks", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{ + "linked-task": "---\nstatus: completed\ngoals:\n - '[[my-goal]]'\n---\n# Linked\n", + }, + map[string]string{ + "my-goal": "---\nstatus: in_progress\n---\n# Success Criteria\n" + + "- [x] done\n# Definition of Done\n- [x] done\n", + }, + ) + defer cleanup() + + goalPath := filepath.Join(vaultPath, "Goals", "my-goal.md") + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + Eventually(runCommand("goal", "complete", "my-goal")).Should(gexec.Exit(0)) + content, err := os.ReadFile(goalPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + Expect(string(content)).To(ContainSubstring("status: completed")) + }) + + It("goal complete refuses an open task linked as a wikilink", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{ + "linked-task": "---\nstatus: todo\ngoals:\n - '[[my-goal]]'\n---\n# Linked\n", + }, + map[string]string{ + "my-goal": "---\nstatus: in_progress\n---\n# Success Criteria\n" + + "- [x] done\n# Definition of Done\n- [x] done\n", + }, + ) + defer cleanup() + + goalPath := filepath.Join(vaultPath, "Goals", "my-goal.md") + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("goal", "complete", "my-goal") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("linked-task")) + content, err := os.ReadFile(goalPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + Expect(string(content)).To(ContainSubstring("status: in_progress")) + }) + + It("goal complete refuses an open task linked as a bare name", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{ + "linked-task": "---\nstatus: todo\ngoals:\n - my-goal\n---\n# Linked\n", + }, + map[string]string{ + "my-goal": "---\nstatus: in_progress\n---\n# Success Criteria\n" + + "- [x] done\n# Definition of Done\n- [x] done\n", + }, + ) + defer cleanup() + + _ = vaultPath + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("goal", "complete", "my-goal") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("linked-task")) + }) + + It("goal complete closes a pre-cutoff goal with no Definition of Done", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{}, + map[string]string{ + "my-goal": "---\nstatus: in_progress\ncreated: \"2026-01-05\"\n---\n" + + "# Success Criteria\n- [x] done\n", + }, + ) + defer cleanup() + + goalPath := filepath.Join(vaultPath, "Goals", "my-goal.md") + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + Eventually(runCommand("goal", "complete", "my-goal")).Should(gexec.Exit(0)) + content, err := os.ReadFile(goalPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + Expect(string(content)).To(ContainSubstring("status: completed")) + }) + + It("goal complete refuses a goal whose Definition of Done section holds no box", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{}, + map[string]string{ + "my-goal": "---\nstatus: in_progress\n---\n# Success Criteria\n" + + "- [x] done\n# Definition of Done\n", + }, + ) + defer cleanup() + + _ = vaultPath + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("goal", "complete", "my-goal") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("# Definition of Done")) + }) + + It("goal complete refuses a post-cutoff goal with no Definition of Done", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{}, + map[string]string{ + "my-goal": "---\nstatus: in_progress\ncreated: \"2026-07-01\"\n---\n" + + "# Success Criteria\n- [x] done\n", + }, + ) + defer cleanup() + + _ = vaultPath + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("goal", "complete", "my-goal") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("# Definition of Done")) + }) + + It("topic complete refuses an open Completion Gate box", func() { + vaultPath, configPath, cleanup := createTempVaultWithTopicPages( + "Topics", + map[string]string{ + "my-topic": "---\nstatus: in_progress\n---\n# Success Criteria\n" + + "- [x] done\n# Completion Gate\n- [ ] an open gate\n", + }, + nil, + ) + defer cleanup() + + topicPath := filepath.Join(vaultPath, "Topics", "my-topic.md") + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("topic", "complete", "my-topic") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("an open gate")) + content, err := os.ReadFile(topicPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + Expect(string(content)).To(ContainSubstring("status: in_progress")) + }) + + It("topic complete refuses a non-terminal member goal", func() { + vaultPath, configPath, cleanup := createTempVaultWithTopicPages( + "Topics", + map[string]string{ + "my-topic": "---\nstatus: in_progress\n---\n# Topic\n## Goals\n" + + "- [[Member Goal]]\n# Success Criteria\n- [x] done\n" + + "# Completion Gate\n- [x] gated\n", + }, + map[string]string{ + "Member Goal": "---\nstatus: in_progress\n---\n# Member Goal\n", + }, + ) + defer cleanup() + + _ = vaultPath + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("topic", "complete", "my-topic") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("Member Goal")) + }) + + It("topic complete reads a member under a ### sub-heading inside ## Goals", func() { + vaultPath, configPath, cleanup := createTempVaultWithTopicPages( + "Topics", + map[string]string{ + "my-topic": "---\nstatus: in_progress\n---\n# Topic\n## Goals\n" + + "### Lever A\n- [[Member Goal]]\n# Success Criteria\n- [x] done\n" + + "# Completion Gate\n- [x] gated\n", + }, + map[string]string{ + "Member Goal": "---\nstatus: in_progress\n---\n# Member Goal\n", + }, + ) + defer cleanup() + + _ = vaultPath + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("topic", "complete", "my-topic") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("Member Goal")) + }) + + It("topic complete reads a member under ## inside # Goals", func() { + vaultPath, configPath, cleanup := createTempVaultWithTopicPages( + "Topics", + map[string]string{ + "my-topic": "---\nstatus: in_progress\n---\n# Topic\n# Goals\n## Sub\n" + + "- [[Member Goal]]\n# Success Criteria\n- [x] done\n" + + "# Completion Gate\n- [x] gated\n", + }, + map[string]string{ + "Member Goal": "---\nstatus: in_progress\n---\n# Member Goal\n", + }, + ) + defer cleanup() + + _ = vaultPath + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + session := runCommand("topic", "complete", "my-topic") + Eventually(session).Should(gexec.Exit(1)) + Expect(string(session.Out.Contents())).To(ContainSubstring("Member Goal")) + }) + + It("topic complete closes a fully ticked topic with terminal member goals", func() { + vaultPath, configPath, cleanup := createTempVaultWithTopicPages( + "Topics", + map[string]string{ + "my-topic": "---\nstatus: in_progress\n---\n# Topic\n## Goals\n" + + "- [[Member Goal]]\n# Success Criteria\n- [x] done\n" + + "# Completion Gate\n- [x] gated\n", + }, + map[string]string{ + "Member Goal": "---\nstatus: completed\n---\n# Member Goal\n", + }, + ) + defer cleanup() + + topicPath := filepath.Join(vaultPath, "Topics", "my-topic.md") + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + Eventually(runCommand("topic", "complete", "my-topic")).Should(gexec.Exit(0)) + content, err := os.ReadFile(topicPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + Expect(string(content)).To(ContainSubstring("status: completed")) + }) + + It("goal complete prints one line per open item and reports them in open_items", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{}, + map[string]string{ + "my-goal": "---\nstatus: in_progress\n---\n# Success Criteria\n" + + "- [ ] first open item\n- [ ] second open item\n" + + "# Definition of Done\n- [x] done\n", + }, + ) + defer cleanup() + + _ = vaultPath + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + plain := runCommand("goal", "complete", "my-goal") + Eventually(plain).Should(gexec.Exit(1)) + lines := strings.Split(strings.TrimSpace(string(plain.Out.Contents())), "\n") + Expect(lines).To(HaveLen(2)) + + jsonSession := runCommand("goal", "complete", "my-goal", "--output", "json") + Eventually(jsonSession).Should(gexec.Exit(1)) + var payload map[string]any + Expect(json.Unmarshal(jsonSession.Out.Contents(), &payload)).To(Succeed()) + openItems, ok := payload["open_items"].([]any) + Expect(ok).To(BeTrue()) + Expect(openItems).To(HaveLen(2)) + }) + + It("goal complete is a no-op on an already-completed goal", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{}, + map[string]string{ + "my-goal": "---\nstatus: completed\n---\n# My Goal\n", + }, + ) + defer cleanup() + + goalPath := filepath.Join(vaultPath, "Goals", "my-goal.md") + sha256OfFile := func() string { + data, err := os.ReadFile(goalPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + return fmt.Sprintf("%x", sha256.Sum256(data)) + } + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + before := sha256OfFile() + Eventually(runCommand("goal", "complete", "my-goal")).Should(gexec.Exit(0)) + Expect(sha256OfFile()).To(Equal(before)) + }) + + It("goal complete is a no-op on an aborted goal", func() { + vaultPath, configPath, cleanup := createTempVaultWithGoals( + map[string]string{}, + map[string]string{ + "my-goal": "---\nstatus: aborted\n---\n# My Goal\n", + }, + ) + defer cleanup() + + goalPath := filepath.Join(vaultPath, "Goals", "my-goal.md") + sha256OfFile := func() string { + data, err := os.ReadFile(goalPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + return fmt.Sprintf("%x", sha256.Sum256(data)) + } + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + before := sha256OfFile() + Eventually(runCommand("goal", "complete", "my-goal")).Should(gexec.Exit(0)) + Expect(sha256OfFile()).To(Equal(before)) + }) + + It("topic complete is a no-op on an aborted topic", func() { + vaultPath, configPath, cleanup := createTempVaultWithTopicPages( + "Topics", + map[string]string{ + "my-topic": "---\nstatus: aborted\n---\n# My Topic\n", + }, + nil, + ) + defer cleanup() + + topicPath := filepath.Join(vaultPath, "Topics", "my-topic.md") + sha256OfFile := func() string { + data, err := os.ReadFile(topicPath) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + return fmt.Sprintf("%x", sha256.Sum256(data)) + } + runCommand := func(args ...string) *gexec.Session { + fullArgs := append([]string{"--config", configPath, "--vault", "test"}, args...) + session, err := gexec.Start( + exec.Command(binPath, fullArgs...), + GinkgoWriter, + GinkgoWriter, + ) + Expect(err).NotTo(HaveOccurred()) + return session + } + + before := sha256OfFile() + Eventually(runCommand("topic", "complete", "my-topic")).Should(gexec.Exit(0)) + Expect(sha256OfFile()).To(Equal(before)) + }) + }) + Describe("vault-cli non-close-out transitions unaffected", func() { var vaultPath, configPath string var cleanup func() @@ -6198,11 +6695,12 @@ page_type: goal Expect(afterRemove).To(Equal(afterSecond - 1)) }) - It("topic complete moves the status to completed and refuses a second complete", func() { + It("topic complete moves the status to completed and is a no-op on a second complete", func() { vaultPath, configPath, cleanup := createTempVaultWithTopicPages( "Topics", map[string]string{ - "Round Trip": "---\nstatus: in_progress\n---\n# Round Trip\n", + "Round Trip": "---\nstatus: in_progress\n---\n# Round Trip\n" + + "# Success Criteria\n- [x] done\n# Completion Gate\n- [x] gated\n", }, nil, ) @@ -6210,6 +6708,12 @@ page_type: goal topicPath := filepath.Join(vaultPath, "Topics", "Round Trip.md") + sha256OfFile := func(path string) string { + data, err := os.ReadFile(path) //#nosec G304 -- test file + Expect(err).NotTo(HaveOccurred()) + return fmt.Sprintf("%x", sha256.Sum256(data)) + } + completeCmd := exec.Command( binPath, "--config", configPath, "--vault", "test", "topic", "complete", "Round Trip", @@ -6222,17 +6726,17 @@ page_type: goal Expect(err).NotTo(HaveOccurred()) Expect(string(completed)).To(ContainSubstring("status: completed")) + beforeSecond := sha256OfFile(topicPath) + secondCmd := exec.Command( binPath, "--config", configPath, "--vault", "test", "topic", "complete", "Round Trip", ) secondSession, err := gexec.Start(secondCmd, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) - Eventually(secondSession).Should(gexec.Exit(1)) + Eventually(secondSession).Should(gexec.Exit(0)) - afterSecond, err := os.ReadFile(topicPath) - Expect(err).NotTo(HaveOccurred()) - Expect(afterSecond).To(Equal(completed)) + Expect(sha256OfFile(topicPath)).To(Equal(beforeSecond)) }) It("topic defer writes defer_date for a relative and an absolute date", func() { diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index cd884d0..a41825f 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -135,6 +135,14 @@ func runMutation( }) } +// printOpenItems writes one stdout line per closure-gate item. A refusal must +// name what is open on stdout; the error itself goes to stderr via Execute. +func printOpenItems(items []string) { + for _, item := range items { + fmt.Println(item) + } +} + // NewRootCommand builds and returns the root cobra command for vault-cli. // Callers can set args and I/O streams before calling ExecuteContext. func NewRootCommand(ctx context.Context) *cobra.Command { @@ -1556,6 +1564,9 @@ func createGoalCompleteCommand( gateSuccessor, ) if err != nil { + if !OutputFormat(*outputFormat).IsJSON() { + printOpenItems(result.OpenItems) + } return result, err } if !OutputFormat(*outputFormat).IsJSON() { @@ -1862,9 +1873,13 @@ func createTopicCompleteCommand( func(ctx context.Context, vault *config.Vault) (ops.MutationResult, error) { storageConfig := storage.NewConfigFromVault(vault) topicStore := storage.NewTopicStorage(storageConfig) - completeOp := ops.NewTopicCompleteOperation(topicStore) + goalStore := storage.NewGoalStorage(storageConfig) + completeOp := ops.NewTopicCompleteOperation(topicStore, goalStore) result, err := completeOp.Execute(ctx, vault.Path, topicName, vault.Name) if err != nil { + if !OutputFormat(*outputFormat).IsJSON() { + printOpenItems(result.OpenItems) + } return result, err } if !OutputFormat(*outputFormat).IsJSON() { diff --git a/pkg/ops/closure_gate.go b/pkg/ops/closure_gate.go new file mode 100644 index 0000000..2c0684c --- /dev/null +++ b/pkg/ops/closure_gate.go @@ -0,0 +1,543 @@ +// 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 ops + +import ( + "context" + "fmt" + "regexp" + "strings" + "time" + + "github.com/bborbe/errors" + + "github.com/bborbe/vault-cli/pkg/domain" + "github.com/bborbe/vault-cli/pkg/storage" +) + +// closureKind selects the section set a closure gate reads. +type closureKind string + +const ( + // closureKindGoal gates a goal on Success Criteria + Definition of Done. + closureKindGoal closureKind = "goal" + // closureKindTopic gates a topic on Success Criteria + Completion Gate. + closureKindTopic closureKind = "topic" +) + +// closureOutcome is the verdict of a closure gate. +type closureOutcome string + +const ( + // closureOutcomeOpen means the page is measurable and at least one box or member is open. + closureOutcomeOpen closureOutcome = "OPEN" + // closureOutcomeUnmeasurable means the page's evidence cannot be read at all. + closureOutcomeUnmeasurable closureOutcome = "UNMEASURABLE" + // closureOutcomeClose means every box is ticked and every member is terminal. + closureOutcomeClose closureOutcome = "CLOSE" + // closureOutcomeTerminal means the page is already completed or aborted. + closureOutcomeTerminal closureOutcome = "TERMINAL" +) + +// closureMember is a linked task (goal kind) or a member goal (topic kind). +// Fields are exported so the external ops_test package can build values. +type closureMember struct { + Name string + Status string +} + +// closureVerdict is the result of checkClosureGate. +type closureVerdict struct { + Outcome closureOutcome + OpenItems []string +} + +// dodRequiredAsOf is the grandfathering cutoff. It is the fourth copy of the +// value: claude-supervisor/scripts/goal-closure-read.py, agents/goal-auditor.md +// and agents/task-auditor.md carry the other three. They move together. +const dodRequiredAsOf = "2026-06-26" + +var ( + // closureCheckboxRegex matches a checkbox item with any bullet marker and any + // single-character marker. Capture 1 is the marker, 2 the item text. + closureCheckboxRegex = regexp.MustCompile(`^[ \t]*[-*+][ \t]+\[(.)\][ \t]*(.*)$`) + + // closureListItemRegex matches any markdown list item, checkbox or not. + closureListItemRegex = regexp.MustCompile(`^[ \t]*([-*+]|\d+\.)[ \t]+`) + + // closureHeadingRegex matches an ATX heading line. Capture 1 is the `#` run. + closureHeadingRegex = regexp.MustCompile(`^(#{1,6})[ \t]+`) + + // closureISODateRegex matches a zero-padded ISO date. + closureISODateRegex = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`) + + // closureGoalEntryRegex matches a Goals-section entry declaration. + closureGoalEntryRegex = regexp.MustCompile(`^- \[\[([^\]]+)\]\]`) +) + +// checkClosureGate reads the page's own closure evidence and returns a verdict. +// It is the single implementation behind both `goal complete` and +// `topic complete`; neither verb may carry a second copy of the rule. +// +// The section set is fixed by kind, never guessed from the page: +// goal -> "# Success Criteria" + "# Definition of Done"; +// topic -> "# Success Criteria" + "# Completion Gate". +// +// The check is read-only. A page already at completed/aborted returns TERMINAL +// with no items. On any refusal OpenItems holds one human-readable string per +// blocking item, in document order (sections first, then members). +func checkClosureGate( + ctx context.Context, + kind closureKind, + content string, + members []closureMember, +) (closureVerdict, error) { + doc := normaliseDocument(content) + fields, err := storage.ParseFrontmatterMap(ctx, []byte(doc)) + if err != nil { + return closureVerdict{}, errors.Wrap(ctx, err, "parse frontmatter") + } + + if status := stringField(fields, "status"); isTerminalStatus(status) { + return closureVerdict{Outcome: closureOutcomeTerminal}, nil + } + + body, err := stripFrontmatter(ctx, doc) + if err != nil { + return closureVerdict{}, err + } + body, fenceOK := stripFencedBlocks(body) + if !fenceOK { + return closureVerdict{ + Outcome: closureOutcomeUnmeasurable, + OpenItems: []string{"unterminated code fence"}, + }, nil + } + + items, unmeasurable := closureSectionItems(kind, body, createdField(fields)) + items = append(items, closureMemberItems(kind, members)...) + + outcome := closureOutcomeClose + switch { + case unmeasurable: + outcome = closureOutcomeUnmeasurable + case len(items) > 0: + outcome = closureOutcomeOpen + } + return closureVerdict{Outcome: outcome, OpenItems: items}, nil +} + +// closureSectionItems walks the kind's fixed section set and returns the open +// section items plus whether any of them is unmeasurable. +func closureSectionItems( + kind closureKind, + body string, + created string, +) (items []string, unmeasurable bool) { + for _, heading := range closureHeadings(kind) { + lines, found := findSection(body, heading) + var sectionItems []string + var sectionUnmeasurable bool + if found { + sectionItems, sectionUnmeasurable = presentSectionItems(kind, heading, lines) + } else { + sectionItems, sectionUnmeasurable = absentSectionItems(kind, heading, created, body) + } + items = append(items, sectionItems...) + unmeasurable = unmeasurable || sectionUnmeasurable + } + return items, unmeasurable +} + +// absentSectionItems handles a section that the page does not carry. +func absentSectionItems( + kind closureKind, + heading string, + created string, + body string, +) ([]string, bool) { + if kind == closureKindGoal && heading == "# Definition of Done" { + exempt, message := grandfatherDefinitionOfDone(created, body) + if exempt { + return nil, false + } + return []string{message}, true + } + return []string{heading + ": section absent"}, true +} + +// presentSectionItems handles a section the page does carry. +func presentSectionItems( + kind closureKind, + heading string, + lines []string, +) ([]string, bool) { + open, total := sectionCheckboxItems(lines) + if total == 0 { + return []string{heading + ": section contains no checkbox"}, true + } + items := open + if kind != closureKindTopic || heading != "# Completion Gate" { + return items, false + } + violations := nonCheckboxListItems(lines) + for _, violation := range violations { + items = append(items, "# Completion Gate: non-checkbox list item: "+violation) + } + return items, len(violations) > 0 +} + +// closureHeadings returns the fixed section set for a kind, in document order. +func closureHeadings(kind closureKind) []string { + if kind == closureKindTopic { + return []string{"# Success Criteria", "# Completion Gate"} + } + return []string{"# Success Criteria", "# Definition of Done"} +} + +// grandfatherDefinitionOfDone reports whether an absent Definition of Done +// section is exempt for a goal, and otherwise the refusal item to record. +func grandfatherDefinitionOfDone(created string, body string) (bool, string) { + if hasDoDShapedHeading(body) { + return false, "# Definition of Done: section absent" + } + if created == "" { + return true, "" + } + if !closureISODateRegex.MatchString(created) { + return false, fmt.Sprintf( + "# Definition of Done: section absent (created %q is not an ISO date)", + created, + ) + } + if created < dodRequiredAsOf { + return true, "" + } + return false, fmt.Sprintf( + "# Definition of Done: section absent (created %s is not before %s)", + created, + dodRequiredAsOf, + ) +} + +// closureMemberItems returns the refusal items for non-terminal members. +func closureMemberItems(kind closureKind, members []closureMember) []string { + var items []string + for _, member := range members { + if !closureMemberOpen(kind, member.Status) { + continue + } + if member.Status == "" { + items = append(items, member.Name) + continue + } + items = append(items, fmt.Sprintf("%s (%s)", member.Name, member.Status)) + } + return items +} + +// closureMemberOpen reports whether a member status blocks a close for the kind. +func closureMemberOpen(kind closureKind, status string) bool { + if status == "" { + return true + } + if kind == closureKindGoal { + switch status { + case string(domain.TaskStatusNext), + string(domain.TaskStatusTodo), + string(domain.TaskStatusInProgress): + return true + default: + return false + } + } + return status != domain.TopicStatusCompleted && status != "aborted" +} + +// isTerminalStatus reports whether a page status is completed or aborted. +func isTerminalStatus(status string) bool { + return status == string(domain.GoalStatusCompleted) || + status == string(domain.GoalStatusAborted) +} + +// stringField reads a string field, treating a non-string value as empty. +func stringField(fields map[string]any, key string) string { + value, _ := fields[key].(string) + return value +} + +// closureDateLayout is the date-only shape the grandfathering cutoff compares. +const closureDateLayout = "2006-01-02" + +// createdField reads the `created` frontmatter value as a bare ISO date. +// +// ⚠️ The value must be COERCED, never type-asserted to string. YAML resolves an +// unquoted `created: 2026-07-01` — and an unquoted RFC3339 timestamp — to +// time.Time, so a string-only accessor yields "", which is indistinguishable +// from an absent field and therefore GRANDFATHERS the Definition of Done. That +// fails open: a post-cutoff goal with no DoD closes unexamined, which is the one +// case the exemption must refuse. Measured 2026-11-19: 70 live goal pages in the +// Personal vault carry the unquoted form. +// +// An absent field returns "" (genuinely grandfathered). A present value of an +// unreadable type returns its raw spelling, so the caller refuses it as +// "not an ISO date" rather than exempting the page. +func createdField(fields map[string]any) string { + value, ok := fields["created"] + if !ok { + return "" + } + switch typed := value.(type) { + case time.Time: + return typed.Format(closureDateLayout) + case string: + return trimToDate(typed) + default: + return fmt.Sprintf("%v", value) + } +} + +// trimToDate returns the date part of a timestamp, or the input unchanged when +// it carries no time component. +func trimToDate(value string) string { + if index := strings.IndexAny(value, "T "); index > 0 { + return value[:index] + } + return value +} + +// normaliseDocument strips one leading BOM and normalises CRLF and CR to LF. +func normaliseDocument(content string) string { + doc := strings.TrimPrefix(content, "\ufeff") + doc = strings.ReplaceAll(doc, "\r\n", "\n") + return strings.ReplaceAll(doc, "\r", "\n") +} + +// frontmatterBody returns the body after the frontmatter block. +func frontmatterBody(doc string) (string, bool) { + const open = "---\n" + const delimiter = "\n---\n" + if !strings.HasPrefix(doc, open) { + return "", false + } + rest := doc[len(open):] + index := strings.Index(rest, delimiter) + if index < 0 { + return "", false + } + return rest[index+len(delimiter):], true +} + +// stripFrontmatter returns the body after the frontmatter block. +func stripFrontmatter(ctx context.Context, doc string) (string, error) { + body, ok := frontmatterBody(doc) + if !ok { + return "", errors.Errorf(ctx, "frontmatter block not found") + } + return body, nil +} + +// stripFencedBlocks drops fenced code blocks and reports whether every fence +// was terminated. +func stripFencedBlocks(body string) (string, bool) { + lines := strings.Split(body, "\n") + kept := make([]string, 0, len(lines)) + var fence string + for _, line := range lines { + trimmed := strings.TrimLeft(line, " \t") + if fence == "" { + if strings.HasPrefix(trimmed, "```") { + fence = "`" + continue + } + if strings.HasPrefix(trimmed, "~~~") { + fence = "~" + continue + } + kept = append(kept, line) + continue + } + if strings.HasPrefix(trimmed, strings.Repeat(fence, 3)) { + fence = "" + } + } + return strings.Join(kept, "\n"), fence == "" +} + +// headingLevel returns the ATX heading level of a line, or 0 for a non-heading. +func headingLevel(line string) int { + matches := closureHeadingRegex.FindStringSubmatch(line) + if matches == nil { + return 0 + } + return len(matches[1]) +} + +// headingText returns the trimmed text of an ATX heading line. +func headingText(line string) string { + matches := closureHeadingRegex.FindStringSubmatch(line) + if matches == nil { + return "" + } + return strings.TrimSpace(line[len(matches[1]):]) +} + +// findSection returns the body lines of the first level-1 heading with the +// given exact text, up to the next level-1 heading or end of document. +func findSection(body string, heading string) ([]string, bool) { + target := strings.TrimSpace(strings.TrimPrefix(heading, "#")) + lines := strings.Split(body, "\n") + start := -1 + for i, line := range lines { + level := headingLevel(line) + if start < 0 { + if level == 1 && headingText(line) == target { + start = i + } + continue + } + if level == 1 { + return lines[start+1 : i], true + } + } + if start < 0 { + return nil, false + } + return lines[start+1:], true +} + +// hasDoDShapedHeading reports whether any line spells a Definition of Done +// heading in any form: ATX, setext text line, or a list item. +func hasDoDShapedHeading(body string) bool { + for _, line := range strings.Split(body, "\n") { + text := strings.TrimSpace(line) + text = strings.TrimSpace(strings.TrimLeft(text, "#")) + if len(text) > 0 && (text[0] == '-' || text[0] == '*' || text[0] == '+') { + rest := text[1:] + if rest == "" || rest[0] == ' ' || rest[0] == '\t' { + text = strings.TrimSpace(rest) + } + } + if text == "Definition of Done" { + return true + } + } + return false +} + +// sectionCheckboxItems returns the open checkbox items and the total checkbox +// count for a section. Only `x` and `X` count as done. +func sectionCheckboxItems(lines []string) ([]string, int) { + var open []string + total := 0 + for _, line := range lines { + matches := closureCheckboxRegex.FindStringSubmatch(line) + if matches == nil { + continue + } + total++ + if matches[1] == "x" || matches[1] == "X" { + continue + } + text := strings.TrimSpace(matches[2]) + if text == "" { + text = strings.TrimSpace(line) + } + open = append(open, text) + } + return open, total +} + +// nonCheckboxListItems returns every list item in lines that is not a checkbox. +func nonCheckboxListItems(lines []string) []string { + var violations []string + for _, line := range lines { + if !closureListItemRegex.MatchString(line) { + continue + } + if closureCheckboxRegex.MatchString(line) { + continue + } + violations = append(violations, strings.TrimSpace(line)) + } + return violations +} + +// parseGoalSectionMembers returns the goal names declared in a topic page's +// Goals section, bounded level-relative. +func parseGoalSectionMembers(content string) []string { + doc := normaliseDocument(content) + body, ok := frontmatterBody(doc) + if !ok { + body = doc + } + body, fenceOK := stripFencedBlocks(body) + if !fenceOK { + return nil + } + + lines := strings.Split(body, "\n") + start := -1 + level := 0 + for i, line := range lines { + current := headingLevel(line) + if current < 1 || current > 2 { + continue + } + if headingText(line) == "Goals" { + start = i + level = current + break + } + } + if start < 0 { + return nil + } + + var names []string + seen := make(map[string]bool) + for _, line := range lines[start+1:] { + current := headingLevel(line) + if current > 0 && current <= level { + break + } + matches := closureGoalEntryRegex.FindStringSubmatch(line) + if matches == nil { + continue + } + name := normaliseGoalLink(matches[1]) + if name == "" || seen[name] { + continue + } + seen[name] = true + names = append(names, name) + } + return names +} + +// normaliseGoalLink strips the wikilink wrapper and any alias/heading suffix +// so '[[Some Goal]]', '[[Some Goal|label]]' and 'Some Goal' compare equal. +func normaliseGoalLink(link string) string { + name := strings.TrimSpace(link) + name = strings.TrimPrefix(name, "[[") + name = strings.TrimSuffix(name, "]]") + if index := strings.Index(name, "|"); index >= 0 { + name = name[:index] + } + if index := strings.Index(name, "#"); index >= 0 { + name = name[:index] + } + return strings.TrimSpace(name) +} + +// closureRefusalMessage builds the single-line error text for a refusal. +func closureRefusalMessage(subject string, items []string) string { + return fmt.Sprintf( + "cannot complete %s: %d closure item(s) open: %s", + subject, + len(items), + strings.Join(items, "; "), + ) +} diff --git a/pkg/ops/closure_gate_test.go b/pkg/ops/closure_gate_test.go new file mode 100644 index 0000000..e948d50 --- /dev/null +++ b/pkg/ops/closure_gate_test.go @@ -0,0 +1,370 @@ +// 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 ops_test + +import ( + "context" + "strings" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/bborbe/vault-cli/pkg/ops" +) + +var _ = Describe("Closure gate", func() { + var ctx context.Context + + BeforeEach(func() { + ctx = context.Background() + }) + + DescribeTable("verdict", + func( + kind ops.ClosureKind, + content string, + members []ops.ClosureMember, + expectErr bool, + expectedOutcome ops.ClosureOutcome, + expectedItemCount int, + contains string, + ) { + verdict, err := ops.CheckClosureGate(ctx, kind, content, members) + if expectErr { + Expect(err).To(HaveOccurred()) + return + } + Expect(err).NotTo(HaveOccurred()) + Expect(verdict.Outcome).To(Equal(expectedOutcome)) + Expect(verdict.OpenItems).To(HaveLen(expectedItemCount)) + if contains != "" { + Expect(strings.Join(verdict.OpenItems, "\n")).To(ContainSubstring(contains)) + } + }, + Entry( + "SC box open", + ops.ClosureKindGoal, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [ ] an open criterion\n"+ + "# Definition of Done\n- [x] done item\n", + nil, + false, + ops.ClosureOutcomeOpen, + 1, + "an open criterion", + ), + Entry( + "DoD section present but empty", + ops.ClosureKindGoal, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n# Definition of Done\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Definition of Done", + ), + Entry( + "DoD absent before cutoff is grandfathered", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: \"2026-06-01\"\n---\n# Success Criteria\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeClose, + 0, + "", + ), + Entry( + "DoD absent with no created is grandfathered", + ops.ClosureKindGoal, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeClose, + 0, + "", + ), + Entry( + "DoD heading in a non-# spelling is unmeasurable", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: \"2026-06-01\"\n---\n# Success Criteria\n- [x] done\n"+ + "## Definition of Done\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Definition of Done", + ), + Entry( + "DoD heading as a bullet is unmeasurable", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: \"2026-06-01\"\n---\n# Success Criteria\n- [x] done\n"+ + "- Definition of Done\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Definition of Done", + ), + Entry( + "DoD heading as setext is unmeasurable", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: \"2026-06-01\"\n---\n# Success Criteria\n- [x] done\n"+ + "Definition of Done\n===\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Definition of Done", + ), + Entry( + "DoD absent on or after cutoff", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: \"2026-06-26\"\n---\n# Success Criteria\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Definition of Done", + ), + Entry( + "DoD absent with an unquoted post-cutoff date is not grandfathered", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: 2026-07-01\n---\n# Success Criteria\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Definition of Done", + ), + Entry( + "DoD absent with an unquoted RFC3339 post-cutoff created is not grandfathered", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: 2026-07-01T00:00:00Z\n---\n# Success Criteria\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Definition of Done", + ), + Entry( + "DoD absent with an unquoted pre-cutoff date is grandfathered", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: 2026-01-05\n---\n# Success Criteria\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeClose, + 0, + "", + ), + Entry( + "DoD absent with a quoted RFC3339 pre-cutoff created is grandfathered", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: \"2026-01-05T00:00:00Z\"\n---\n# Success Criteria\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeClose, + 0, + "", + ), + Entry( + "DoD absent with non-ISO created", + ops.ClosureKindGoal, + "---\nstatus: in_progress\ncreated: \"15.01.2026\"\n---\n# Success Criteria\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Definition of Done", + ), + Entry( + "star bullet open box", + ops.ClosureKindGoal, + "---\nstatus: in_progress\n---\n# Success Criteria\n* [ ] open\n# Definition of Done\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeOpen, + 1, + "open", + ), + Entry( + "unrecognised dash marker", + ops.ClosureKindGoal, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [-] open\n# Definition of Done\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeOpen, + 1, + "open", + ), + Entry( + "unrecognised question marker", + ops.ClosureKindGoal, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [?] open\n# Definition of Done\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeOpen, + 1, + "open", + ), + Entry( + "box inside fenced block is not a box", + ops.ClosureKindGoal, + "---\nstatus: in_progress\n---\n# Success Criteria\n```\n- [ ] example\n```\n"+ + "# Definition of Done\n- [x] done\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "# Success Criteria", + ), + Entry( + "unterminated fence", + ops.ClosureKindGoal, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n```\n- [ ] example\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "unterminated code fence", + ), + Entry( + "BOM prefixed CRLF page", + ops.ClosureKindGoal, + "\ufeff---\r\nstatus: in_progress\r\ncreated: \"2026-06-01\"\r\n---\r\n"+ + "# Success Criteria\r\n- [x] done\r\n", + nil, + false, + ops.ClosureOutcomeClose, + 0, + "", + ), + Entry( + "Completion Gate box open", + ops.ClosureKindTopic, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n# Completion Gate\n- [ ] gate\n", + nil, + false, + ops.ClosureOutcomeOpen, + 1, + "gate", + ), + Entry( + "Completion Gate mixes a checkbox with an ordered item", + ops.ClosureKindTopic, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n"+ + "# Completion Gate\n- [x] done\n1. an ordered item\n", + nil, + false, + ops.ClosureOutcomeUnmeasurable, + 1, + "an ordered item", + ), + Entry( + "member goal not terminal", + ops.ClosureKindTopic, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n"+ + "# Completion Gate\n- [x] gated\n", + []ops.ClosureMember{{Name: "member", Status: "in_progress"}}, + false, + ops.ClosureOutcomeOpen, + 1, + "member", + ), + Entry( + "member goal terminal", + ops.ClosureKindTopic, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n"+ + "# Completion Gate\n- [x] gated\n", + []ops.ClosureMember{{Name: "member", Status: "completed"}}, + false, + ops.ClosureOutcomeClose, + 0, + "", + ), + Entry( + "topic with no Goals section", + ops.ClosureKindTopic, + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n"+ + "# Completion Gate\n- [x] gated\n", + nil, + false, + ops.ClosureOutcomeClose, + 0, + "", + ), + Entry( + "already completed page", + ops.ClosureKindGoal, + "---\nstatus: completed\n---\n", + nil, + false, + ops.ClosureOutcomeTerminal, + 0, + "", + ), + Entry( + "already aborted page", + ops.ClosureKindGoal, + "---\nstatus: aborted\n---\n", + nil, + false, + ops.ClosureOutcomeTerminal, + 0, + "", + ), + Entry( + "missing frontmatter", + ops.ClosureKindGoal, + "# Success Criteria\n- [x] done\n", + nil, + true, + ops.ClosureOutcomeOpen, + 0, + "", + ), + ) +}) + +var _ = Describe("Closure gate Goals section", func() { + DescribeTable("members", + func(content string, expected []string) { + Expect(ops.ParseGoalSectionMembers(content)).To(Equal(expected)) + }, + Entry( + "reads a ## Goals list", + "## Goals\n- [[A]]\n- [[B]]\n# Next\n", + []string{"A", "B"}, + ), + Entry( + "runs past a ### sub-heading inside ## Goals", + "## Goals\n- [[A]]\n- [[B]]\n### Lever A\n- [[C]]\n# Next\n", + []string{"A", "B", "C"}, + ), + Entry( + "runs past ## inside # Goals", + "# Goals\n- [[A]]\n## Sub\n- [[D]]\n# Other\n", + []string{"A", "D"}, + ), + Entry( + "stops at the next # heading after # Goals", + "# Goals\n- [[A]]\n# Other\n- [[E]]\n", + []string{"A"}, + ), + Entry( + "ignores non-declaration lines", + "## Goals\n1. [[X]]\n**[[Y]]**\nsome [[Z]] here\n- [[Real]]\n", + []string{"Real"}, + ), + Entry( + "strips an alias", + "## Goals\n- [[Name|label]]\n", + []string{"Name"}, + ), + Entry( + "returns empty without a Goals heading", + "# Other\n- [[A]]\n", + []string(nil), + ), + ) +}) diff --git a/pkg/ops/complete.go b/pkg/ops/complete.go index 49f2727..1df65d3 100644 --- a/pkg/ops/complete.go +++ b/pkg/ops/complete.go @@ -77,6 +77,9 @@ type MutationResult struct { InProgress int `json:"inprogress,omitempty"` Completed int `json:"completed,omitempty"` Total int `json:"total,omitempty"` + // OpenItems lists every closure item that blocks a goal or topic close, in + // document order. Populated only on a closure-gate refusal. + OpenItems []string `json:"open_items,omitempty"` } // Execute marks a task as complete and updates the associated goal. diff --git a/pkg/ops/export_test.go b/pkg/ops/export_test.go index c587674..cde5619 100644 --- a/pkg/ops/export_test.go +++ b/pkg/ops/export_test.go @@ -30,3 +30,29 @@ var PersistGoalSessionID = persistGoalSessionID // PersistTopicSessionID exposes persistTopicSessionID for the external ops_test package. var PersistTopicSessionID = persistTopicSessionID + +// CheckClosureGate exposes checkClosureGate for the external ops_test package. +var CheckClosureGate = checkClosureGate + +// ParseGoalSectionMembers exposes parseGoalSectionMembers for ops_test. +var ParseGoalSectionMembers = parseGoalSectionMembers + +// Closure kinds and outcomes for ops_test. +const ( + ClosureKindGoal = closureKindGoal + ClosureKindTopic = closureKindTopic + ClosureOutcomeOpen = closureOutcomeOpen + ClosureOutcomeUnmeasurable = closureOutcomeUnmeasurable + ClosureOutcomeClose = closureOutcomeClose + ClosureOutcomeTerminal = closureOutcomeTerminal +) + +// ClosureKind and ClosureOutcome expose the gate's enum types to ops_test. +type ClosureKind = closureKind + +type ClosureOutcome = closureOutcome + +// ClosureMember and ClosureVerdict expose the gate's value types to ops_test. +type ClosureMember = closureMember + +type ClosureVerdict = closureVerdict diff --git a/pkg/ops/goal_complete.go b/pkg/ops/goal_complete.go index ad89a29..b495f5d 100644 --- a/pkg/ops/goal_complete.go +++ b/pkg/ops/goal_complete.go @@ -6,8 +6,6 @@ package ops import ( "context" - "fmt" - "strings" "github.com/bborbe/errors" libtime "github.com/bborbe/time" @@ -70,17 +68,31 @@ func (g *goalCompleteOperation) Execute( ) } - if goal.Status() == domain.GoalStatusCompleted { - msg := fmt.Sprintf("goal %q is already completed", goalName) - return MutationResult{Success: false, Error: msg}, errors.Errorf(ctx, "%s", msg) + if goal.Status() == domain.GoalStatusCompleted || goal.Status() == domain.GoalStatusAborted { + return MutationResult{Success: true, Name: goal.Name, Vault: vaultName}, nil } + var members []closureMember if !force { - if result, err := g.checkOpenTasks(ctx, vaultPath, goalName); err != nil { - return result, err + members, err = g.linkedTaskMembers(ctx, vaultPath, goalName) + if err != nil { + return MutationResult{Success: false, Error: err.Error()}, err } } + verdict, err := checkClosureGate(ctx, closureKindGoal, string(goal.Content), members) + if err != nil { + return MutationResult{Success: false, Error: err.Error()}, err + } + if verdict.Outcome == closureOutcomeTerminal { + return MutationResult{Success: true, Name: goal.Name, Vault: vaultName}, nil + } + if verdict.Outcome != closureOutcomeClose { + msg := closureRefusalMessage("goal", verdict.OpenItems) + return MutationResult{Success: false, Error: msg, OpenItems: verdict.OpenItems}, + errors.Errorf(ctx, "%s", msg) + } + // One-step close-out: persist reason and successor before the status // transition so both land in a single WriteGoal. Fields are written only // when provided — the two-step close-out (fields already in the file) works @@ -140,61 +152,34 @@ func (g *goalCompleteOperation) setCompletedStatus( return MutationResult{}, nil } -func (g *goalCompleteOperation) checkOpenTasks( +// linkedTaskMembers returns every task linked to the goal, as closure members. +// It is the only reader of the task relation; the gate decides which statuses +// are open. +func (g *goalCompleteOperation) linkedTaskMembers( ctx context.Context, vaultPath string, goalName string, -) (MutationResult, error) { +) ([]closureMember, error) { tasks, err := g.taskStorage.ListTasks(ctx, vaultPath) if err != nil { - return MutationResult{ - Success: false, - Error: err.Error(), - }, errors.Wrap( - ctx, - err, - "list tasks", - ) + return nil, errors.Wrap(ctx, err, "list tasks") } - var openTasks []*domain.Task + members := make([]closureMember, 0, len(tasks)) for _, task := range tasks { if !taskLinkedToGoal(task, goalName) { continue } - if task.Status() == domain.TaskStatusNext || - task.Status() == domain.TaskStatusTodo || - task.Status() == domain.TaskStatusInProgress { - openTasks = append(openTasks, task) - } - } - - if len(openTasks) > 0 { - taskList := joinTaskNames(openTasks) - msg := fmt.Sprintf( - "cannot complete goal: %d task(s) still open: %s", - len(openTasks), - taskList, - ) - return MutationResult{Success: false, Error: msg}, errors.Errorf(ctx, "%s", msg) + members = append(members, closureMember{Name: task.Name, Status: string(task.Status())}) } - - return MutationResult{}, nil + return members, nil } func taskLinkedToGoal(task *domain.Task, goalName string) bool { - for _, g := range task.Goals() { - if g == goalName { + for _, goal := range task.Goals() { + if normaliseGoalLink(goal) == goalName { return true } } return false } - -func joinTaskNames(tasks []*domain.Task) string { - names := make([]string, len(tasks)) - for i, t := range tasks { - names[i] = fmt.Sprintf("%s (%s)", t.Name, t.Status()) - } - return strings.Join(names, ", ") -} diff --git a/pkg/ops/goal_complete_test.go b/pkg/ops/goal_complete_test.go index dbf9253..da74e2d 100644 --- a/pkg/ops/goal_complete_test.go +++ b/pkg/ops/goal_complete_test.go @@ -17,6 +17,12 @@ import ( "github.com/bborbe/vault-cli/pkg/ops" ) +// completeGoalContent is a closure-complete goal body. The absent +// # Definition of Done section is grandfathered (no created), so it closes. +func completeGoalContent(status string) domain.Content { + return domain.Content("---\nstatus: " + status + "\n---\n# Success Criteria\n- [x] done\n") +} + var _ = Describe("GoalCompleteOperation", func() { var ( ctx context.Context @@ -50,7 +56,7 @@ var _ = Describe("GoalCompleteOperation", func() { goal = domain.NewGoal( map[string]any{"status": "active", "aborted_reason": "test reason", "gate_successor": "none"}, domain.FileMetadata{Name: goalName}, - domain.Content(""), + completeGoalContent("active"), ) mockGoalStorage.FindGoalByNameReturns(goal, nil) mockGoalStorage.WriteGoalReturns(nil) @@ -91,9 +97,170 @@ var _ = Describe("GoalCompleteOperation", func() { mockGoalStorage.FindGoalByNameReturns(goal, nil) }) - It("returns error", func() { + It("returns no error", func() { + Expect(err).To(BeNil()) + Expect(result.Success).To(BeTrue()) + Expect(result.Name).To(Equal(goalName)) + }) + + It("does not write goal", func() { + Expect(mockGoalStorage.WriteGoalCallCount()).To(Equal(0)) + }) + + It("reports no open items", func() { + Expect(result.OpenItems).To(BeEmpty()) + }) + }) + + Context("goal already aborted", func() { + BeforeEach(func() { + _ = goal.SetStatus(domain.GoalStatusAborted) + mockGoalStorage.FindGoalByNameReturns(goal, nil) + }) + + It("returns no error", func() { + Expect(err).To(BeNil()) + Expect(result.Success).To(BeTrue()) + Expect(result.Name).To(Equal(goalName)) + }) + + It("does not write goal", func() { + Expect(mockGoalStorage.WriteGoalCallCount()).To(Equal(0)) + }) + }) + + Context("open criterion blocks completion", func() { + BeforeEach(func() { + goal = domain.NewGoal( + map[string]any{"status": "in_progress"}, + domain.FileMetadata{Name: goalName}, + domain.Content( + "---\nstatus: in_progress\n---\n# Success Criteria\n- [ ] an open criterion\n"+ + "# Definition of Done\n- [x] done\n", + ), + ) + mockGoalStorage.FindGoalByNameReturns(goal, nil) + }) + + It("returns an error naming the criterion", func() { + Expect(err).NotTo(BeNil()) + Expect(err.Error()).To(ContainSubstring("an open criterion")) + }) + + It("does not write goal", func() { + Expect(mockGoalStorage.WriteGoalCallCount()).To(Equal(0)) + }) + + It("reports the single open item", func() { + Expect(result.OpenItems).To(HaveLen(1)) + }) + }) + + Context("force does not bypass an open criterion", func() { + BeforeEach(func() { + force = true + goal = domain.NewGoal( + map[string]any{"status": "in_progress"}, + domain.FileMetadata{Name: goalName}, + domain.Content( + "---\nstatus: in_progress\n---\n# Success Criteria\n- [ ] an open criterion\n"+ + "# Definition of Done\n- [x] done\n", + ), + ) + mockGoalStorage.FindGoalByNameReturns(goal, nil) + }) + + It("returns an error naming the criterion", func() { Expect(err).NotTo(BeNil()) - Expect(err.Error()).To(ContainSubstring("already completed")) + Expect(err.Error()).To(ContainSubstring("an open criterion")) + }) + + It("does not write goal", func() { + Expect(mockGoalStorage.WriteGoalCallCount()).To(Equal(0)) + }) + + It("reports the open item", func() { + Expect(result.OpenItems).To(ContainElement(ContainSubstring("an open criterion"))) + }) + }) + + Context("bracketed goal link blocks completion", func() { + BeforeEach(func() { + task := domain.NewTask( + map[string]any{"status": "todo"}, + domain.FileMetadata{Name: "linked-task"}, + domain.Content(""), + ) + task.SetGoals([]string{"[[" + goalName + "]]"}) + mockTaskStorage.ListTasksReturns([]*domain.Task{task}, nil) + }) + + It("returns an error naming the task", func() { + Expect(err).NotTo(BeNil()) + Expect(err.Error()).To(ContainSubstring("linked-task")) + }) + + It("does not write goal", func() { + Expect(mockGoalStorage.WriteGoalCallCount()).To(Equal(0)) + }) + }) + + Context("bare goal link blocks completion", func() { + BeforeEach(func() { + task := domain.NewTask( + map[string]any{"status": "todo"}, + domain.FileMetadata{Name: "linked-task"}, + domain.Content(""), + ) + task.SetGoals([]string{goalName}) + mockTaskStorage.ListTasksReturns([]*domain.Task{task}, nil) + }) + + It("returns an error naming the task", func() { + Expect(err).NotTo(BeNil()) + Expect(err.Error()).To(ContainSubstring("linked-task")) + }) + + It("does not write goal", func() { + Expect(mockGoalStorage.WriteGoalCallCount()).To(Equal(0)) + }) + }) + + Context("aliased goal link blocks completion", func() { + BeforeEach(func() { + task := domain.NewTask( + map[string]any{"status": "todo"}, + domain.FileMetadata{Name: "linked-task"}, + domain.Content(""), + ) + task.SetGoals([]string{"[[" + goalName + "|label]]"}) + mockTaskStorage.ListTasksReturns([]*domain.Task{task}, nil) + }) + + It("returns an error naming the task", func() { + Expect(err).NotTo(BeNil()) + Expect(err.Error()).To(ContainSubstring("linked-task")) + }) + + It("does not write goal", func() { + Expect(mockGoalStorage.WriteGoalCallCount()).To(Equal(0)) + }) + }) + + Context("heading-suffixed goal link blocks completion", func() { + BeforeEach(func() { + task := domain.NewTask( + map[string]any{"status": "todo"}, + domain.FileMetadata{Name: "linked-task"}, + domain.Content(""), + ) + task.SetGoals([]string{"[[" + goalName + "#heading]]"}) + mockTaskStorage.ListTasksReturns([]*domain.Task{task}, nil) + }) + + It("returns an error naming the task", func() { + Expect(err).NotTo(BeNil()) + Expect(err.Error()).To(ContainSubstring("linked-task")) }) It("does not write goal", func() { @@ -262,7 +429,7 @@ var _ = Describe("GoalCompleteOperation", func() { goal = domain.NewGoal( map[string]any{"status": "active"}, domain.FileMetadata{Name: goalName}, - domain.Content(""), + completeGoalContent("active"), ) mockGoalStorage.FindGoalByNameReturns(goal, nil) }) @@ -294,7 +461,7 @@ var _ = Describe("GoalCompleteOperation", func() { goal = domain.NewGoal( map[string]any{"status": "active"}, domain.FileMetadata{Name: goalName}, - domain.Content(""), + completeGoalContent("active"), ) mockGoalStorage.FindGoalByNameReturns(goal, nil) reason = "achieved" @@ -325,7 +492,7 @@ var _ = Describe("GoalCompleteOperation", func() { goal = domain.NewGoal( map[string]any{"status": "in_progress", "phase": "planning"}, domain.FileMetadata{Name: goalName}, - domain.Content(""), + completeGoalContent("in_progress"), ) mockGoalStorage.FindGoalByNameReturns(goal, nil) }) @@ -345,7 +512,7 @@ var _ = Describe("GoalCompleteOperation", func() { goal = domain.NewGoal( map[string]any{"status": "in_progress", "phase": "execution"}, domain.FileMetadata{Name: goalName}, - domain.Content(""), + completeGoalContent("in_progress"), ) mockGoalStorage.FindGoalByNameReturns(goal, nil) }) diff --git a/pkg/ops/topic_complete.go b/pkg/ops/topic_complete.go index f4c2561..cc4dea3 100644 --- a/pkg/ops/topic_complete.go +++ b/pkg/ops/topic_complete.go @@ -6,7 +6,6 @@ package ops import ( "context" - "fmt" "github.com/bborbe/errors" @@ -25,17 +24,30 @@ type TopicCompleteOperation interface { } // NewTopicCompleteOperation creates a new topic complete operation. -func NewTopicCompleteOperation(topicStorage storage.TopicStorage) TopicCompleteOperation { - return &topicCompleteOperation{topicStorage: topicStorage} +// +// goalStorage resolves the member goals named in the topic's Goals section: +// the closure gate needs each member's status, and topics carry no task +// relation of their own. +func NewTopicCompleteOperation( + topicStorage storage.TopicStorage, + goalStorage storage.GoalStorage, +) TopicCompleteOperation { + return &topicCompleteOperation{ + topicStorage: topicStorage, + goalStorage: goalStorage, + } } type topicCompleteOperation struct { topicStorage storage.TopicStorage + goalStorage storage.GoalStorage } // Execute marks a topic as completed. // -// Unlike the goal variant there is no open-task gate and no close-out machinery: +// The closure gate reads the topic's own Success Criteria and Completion Gate +// boxes and the terminality of every member goal. A topic already at completed +// or aborted is a no-op. There is no open-task gate and no close-out machinery: // topics carry no task linkage and no close-out status, so the only observable // transition is the status field. func (o *topicCompleteOperation) Execute( @@ -49,9 +61,25 @@ func (o *topicCompleteOperation) Execute( return MutationResult{Success: false, Error: err.Error()}, errors.Wrap(ctx, err, "find topic") } - if topic.GetField("status") == domain.TopicStatusCompleted { - msg := fmt.Sprintf("topic %q is already completed", topicName) - return MutationResult{Success: false, Error: msg}, errors.Errorf(ctx, "%s", msg) + if status := topic.GetField("status"); status == domain.TopicStatusCompleted || status == "aborted" { + return MutationResult{Success: true, Name: topic.Name, Vault: vaultName}, nil + } + + members, err := o.goalMembers(ctx, vaultPath, string(topic.Content)) + if err != nil { + return MutationResult{Success: false, Error: err.Error()}, err + } + verdict, err := checkClosureGate(ctx, closureKindTopic, string(topic.Content), members) + if err != nil { + return MutationResult{Success: false, Error: err.Error()}, err + } + if verdict.Outcome == closureOutcomeTerminal { + return MutationResult{Success: true, Name: topic.Name, Vault: vaultName}, nil + } + if verdict.Outcome != closureOutcomeClose { + msg := closureRefusalMessage("topic", verdict.OpenItems) + return MutationResult{Success: false, Error: msg, OpenItems: verdict.OpenItems}, + errors.Errorf(ctx, "%s", msg) } if err := topic.SetField(ctx, "status", domain.TopicStatusCompleted); err != nil { @@ -64,3 +92,27 @@ func (o *topicCompleteOperation) Execute( return MutationResult{Success: true, Name: topic.Name, Vault: vaultName}, nil } + +// goalMembers resolves each goal named in the topic's Goals section to its +// status. A member whose goal file does not exist reads as open (Status ""): +// an unresolvable member is never treated as terminal. +func (o *topicCompleteOperation) goalMembers( + ctx context.Context, + vaultPath string, + content string, +) ([]closureMember, error) { + names := parseGoalSectionMembers(content) + members := make([]closureMember, 0, len(names)) + for _, name := range names { + goal, err := o.goalStorage.FindGoalByName(ctx, vaultPath, name) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + members = append(members, closureMember{Name: name}) + continue + } + return nil, errors.Wrapf(ctx, err, "find goal %s", name) + } + members = append(members, closureMember{Name: name, Status: string(goal.Status())}) + } + return members, nil +} diff --git a/pkg/ops/topic_complete_test.go b/pkg/ops/topic_complete_test.go index 9f1ebd3..d4000bd 100644 --- a/pkg/ops/topic_complete_test.go +++ b/pkg/ops/topic_complete_test.go @@ -13,8 +13,18 @@ import ( "github.com/bborbe/vault-cli/mocks" "github.com/bborbe/vault-cli/pkg/domain" "github.com/bborbe/vault-cli/pkg/ops" + "github.com/bborbe/vault-cli/pkg/storage" ) +// completeTopicContent is a closure-complete topic body: every Success Criteria +// and Completion Gate box is ticked. +func completeTopicContent(status string) domain.Content { + return domain.Content( + "---\nstatus: " + status + "\n---\n# Success Criteria\n- [x] done\n" + + "# Completion Gate\n- [x] gated\n", + ) +} + var _ = Describe("TopicCompleteOperation", func() { var ( ctx context.Context @@ -22,6 +32,7 @@ var _ = Describe("TopicCompleteOperation", func() { result ops.MutationResult op ops.TopicCompleteOperation mockTopicStorage *mocks.TopicStorage + mockGoalStorage *mocks.GoalStorage vaultPath string topicName string vaultName string @@ -31,7 +42,8 @@ var _ = Describe("TopicCompleteOperation", func() { BeforeEach(func() { ctx = context.Background() mockTopicStorage = &mocks.TopicStorage{} - op = ops.NewTopicCompleteOperation(mockTopicStorage) + mockGoalStorage = &mocks.GoalStorage{} + op = ops.NewTopicCompleteOperation(mockTopicStorage, mockGoalStorage) vaultPath = "/path/to/vault" topicName = "my-topic" vaultName = "test-vault" @@ -39,7 +51,7 @@ var _ = Describe("TopicCompleteOperation", func() { topic = domain.NewTopic( map[string]any{"status": "in_progress"}, domain.FileMetadata{Name: topicName, FilePath: "/vault/Topics/my-topic.md"}, - domain.Content("---\nstatus: in_progress\n---\n"), + completeTopicContent("in_progress"), ) mockTopicStorage.FindTopicByNameReturns(topic, nil) mockTopicStorage.WriteTopicReturns(nil) @@ -87,7 +99,7 @@ var _ = Describe("TopicCompleteOperation", func() { topic = domain.NewTopic( map[string]any{}, domain.FileMetadata{Name: topicName, FilePath: "/vault/Topics/my-topic.md"}, - domain.Content(""), + completeTopicContent(""), ) mockTopicStorage.FindTopicByNameReturns(topic, nil) }) @@ -105,7 +117,7 @@ var _ = Describe("TopicCompleteOperation", func() { topic = domain.NewTopic( map[string]any{"status": "whatever"}, domain.FileMetadata{Name: topicName, FilePath: "/vault/Topics/my-topic.md"}, - domain.Content(""), + completeTopicContent("whatever"), ) mockTopicStorage.FindTopicByNameReturns(topic, nil) }) @@ -123,19 +135,110 @@ var _ = Describe("TopicCompleteOperation", func() { topic = domain.NewTopic( map[string]any{"status": domain.TopicStatusCompleted}, domain.FileMetadata{Name: topicName, FilePath: "/vault/Topics/my-topic.md"}, - domain.Content(""), + completeTopicContent(domain.TopicStatusCompleted), + ) + mockTopicStorage.FindTopicByNameReturns(topic, nil) + }) + + It("returns no error", func() { + Expect(err).To(BeNil()) + Expect(result.Success).To(BeTrue()) + }) + + It("does not write the topic", func() { + Expect(mockTopicStorage.WriteTopicCallCount()).To(Equal(0)) + }) + }) + + Context("topic already aborted", func() { + BeforeEach(func() { + topic = domain.NewTopic( + map[string]any{"status": "aborted"}, + domain.FileMetadata{Name: topicName, FilePath: "/vault/Topics/my-topic.md"}, + completeTopicContent("aborted"), ) mockTopicStorage.FindTopicByNameReturns(topic, nil) }) - It("returns an error naming the refusal", func() { + It("returns no error", func() { + Expect(err).To(BeNil()) + Expect(result.Success).To(BeTrue()) + }) + + It("does not write the topic", func() { + Expect(mockTopicStorage.WriteTopicCallCount()).To(Equal(0)) + }) + }) + + Context("open Completion Gate box blocks completion", func() { + BeforeEach(func() { + topic = domain.NewTopic( + map[string]any{"status": "in_progress"}, + domain.FileMetadata{Name: topicName, FilePath: "/vault/Topics/my-topic.md"}, + domain.Content( + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n"+ + "# Completion Gate\n- [ ] an open gate\n", + ), + ) + mockTopicStorage.FindTopicByNameReturns(topic, nil) + }) + + It("returns an error naming the gate", func() { Expect(err).NotTo(BeNil()) - Expect(err.Error()).To(ContainSubstring("topic \"my-topic\" is already completed")) + Expect(err.Error()).To(ContainSubstring("an open gate")) }) - It("returns a failed result", func() { - Expect(result.Success).To(BeFalse()) - Expect(result.Error).To(ContainSubstring("already completed")) + It("does not write the topic", func() { + Expect(mockTopicStorage.WriteTopicCallCount()).To(Equal(0)) + }) + }) + + Context("non-terminal member goal blocks completion", func() { + BeforeEach(func() { + topic = domain.NewTopic( + map[string]any{"status": "in_progress"}, + domain.FileMetadata{Name: topicName, FilePath: "/vault/Topics/my-topic.md"}, + domain.Content( + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n"+ + "# Completion Gate\n- [x] gated\n# Goals\n- [[my-member]]\n", + ), + ) + mockTopicStorage.FindTopicByNameReturns(topic, nil) + member := domain.NewGoal( + map[string]any{"status": "in_progress"}, + domain.FileMetadata{Name: "my-member"}, + domain.Content(""), + ) + mockGoalStorage.FindGoalByNameReturns(member, nil) + }) + + It("returns an error naming the member", func() { + Expect(err).NotTo(BeNil()) + Expect(err.Error()).To(ContainSubstring("my-member")) + }) + + It("does not write the topic", func() { + Expect(mockTopicStorage.WriteTopicCallCount()).To(Equal(0)) + }) + }) + + Context("member goal missing from the vault blocks completion", func() { + BeforeEach(func() { + topic = domain.NewTopic( + map[string]any{"status": "in_progress"}, + domain.FileMetadata{Name: topicName, FilePath: "/vault/Topics/my-topic.md"}, + domain.Content( + "---\nstatus: in_progress\n---\n# Success Criteria\n- [x] done\n"+ + "# Completion Gate\n- [x] gated\n# Goals\n- [[missing-member]]\n", + ), + ) + mockTopicStorage.FindTopicByNameReturns(topic, nil) + mockGoalStorage.FindGoalByNameReturns(nil, storage.ErrNotFound) + }) + + It("returns an error naming the missing member", func() { + Expect(err).NotTo(BeNil()) + Expect(err.Error()).To(ContainSubstring("missing-member")) }) It("does not write the topic", func() { diff --git a/prompts/completed/284-spec-069-goal-topic-closure-gate.md b/prompts/completed/284-spec-069-goal-topic-closure-gate.md new file mode 100644 index 0000000..104c324 --- /dev/null +++ b/prompts/completed/284-spec-069-goal-topic-closure-gate.md @@ -0,0 +1,595 @@ +--- +status: completed +spec: [069-bug-goal-topic-closure-gate] +summary: Added a shared pkg/ops closure gate, wired it into goal/topic complete with open_items reporting and terminal no-ops, and covered it with unit and integration tests +execution_id: vault-cli-closure-gate-exec-284-spec-069-goal-topic-closure-gate +dark-factory-version: v0.198.17 +created: "2026-11-18T22:55:00Z" +queued: "2026-11-18T23:06:57Z" +started: "2026-11-18T23:06:58Z" +completed: "2026-11-18T23:19:37Z" +--- + +# Gate `goal complete` and `topic complete` on their own closure evidence + + +- `vault-cli goal complete` refuses to close a goal while any `# Success Criteria` or `# Definition of Done` box is open, and names every open box. +- `vault-cli topic complete` refuses to close a topic while any `# Success Criteria` or `# Completion Gate` box is open, or while any goal listed in the topic's Goals section is not `completed`/`aborted`. +- An open task linked to a goal as `[[Some Goal]]` now blocks the close exactly as the bare name `Some Goal` already did. +- A refusal exits 1, prints one line per open item on stdout, and reports the same items as `open_items` in `--output json`. +- A page that is already `completed` or `aborted` is a no-op: exit 0, no write, file digest unchanged. +- Goals created before 2026-06-26 with no `# Definition of Done` section still close, but only when that section is genuinely absent — an empty or oddly-spelled DoD heading refuses. +- A checkbox inside a fenced code block is an example, never a box; an unterminated fence refuses the close. +- Both commands share one implementation, so the rule cannot drift between them. +- `task complete`, `objective complete`, and the existing `--force` semantics are unchanged. + + + +Implement the vault's closure rule in one shared `pkg/ops` check and wire it into `goal complete` and `topic complete`, so a goal or topic can only close on its own recorded evidence. This is spec 069, deliberately one prompt: the spec's § Suggested Decomposition fixes a single prompt because a multi-prompt split cannot be sorted into dependency order by dark-factory's unprefixed-filename numbering. + + + +Read `CLAUDE.md` and `docs/dod.md` for project conventions and the Definition of Done. + +Read these files fully before changing anything: + +- `specs/in-progress/069-bug-goal-topic-closure-gate.md` — the whole spec. Desired Behavior 1-12, Constraints, Failure Modes, and the last Acceptance Criterion (the table-test case list) are all binding. +- `pkg/ops/complete.go` — `MutationResult` (line 66) is where the new `OpenItems` field belongs. `checkSubtaskCompletion` (line 234) is the existing whole-page box gate for tasks; it is the model, not a target. `countCheckboxStates` uses `storage.CheckboxRegex`, which accepts only `-`/`*` bullets and only ` `/`x`/`/` markers — it is **not** reusable here (see requirement 1.5). +- `pkg/ops/goal_complete.go` — the whole file. `Execute` currently refuses an already-`completed` goal (lines 73-76), then runs `checkOpenTasks` unless `force` (78-82), then writes. `taskLinkedToGoal` (185-192) compares `g == goalName` over raw `goals:` entries. `joinTaskNames` (194-200) formats `name (status)`. +- `pkg/ops/topic_complete.go` — the whole file. `Execute` (41-66) finds, refuses an already-`completed` topic (52-55), sets `status`, writes. No gate, no `--force`, no goal storage dependency. +- `pkg/ops/goal_complete_test.go` — the `Context("goal already completed")` block (lines 88-101) must be **inverted, not deleted**. Every other context that expects a successful close needs a closure-complete fixture body (requirement 6.3). +- `pkg/ops/topic_complete_test.go` — the `Context("topic already completed")` block (lines 121-144) must be **inverted, not deleted**. The shared `BeforeEach` fixture body (line 42) and the two alternate fixtures (lines 90, 108) need closure-complete bodies (requirement 6.4). +- `pkg/ops/export_test.go` — the established mechanism for exposing unexported `pkg/ops` symbols to the external `ops_test` package. Add the closure-gate aliases here (requirement 6.1). +- `pkg/ops/ops_suite_test.go` — `TestSuite`; Ginkgo v2/Gomega, external test package. `DescribeTable` is already used in `pkg/ops/escalation_test.go`, `task_approve_test.go`, `lint_test.go`. +- `pkg/domain/goal.go` / `pkg/domain/topic.go` / `pkg/domain/task_status.go` — `Goal` and `Topic` embed their frontmatter and carry `Content domain.Content` (the full raw markdown file, frontmatter included). Status constants: `domain.GoalStatusCompleted`, `domain.GoalStatusAborted`, `domain.TaskStatusNext`, `domain.TaskStatusTodo`, `domain.TaskStatusInProgress`, `domain.TopicStatusCompleted`. +- `pkg/domain/frontmatter_map.go` — `GetString(key)` / `Get(key)` on the embedded `FrontmatterMap`; `GetField("created")` on both `GoalFrontmatter` and `TopicFrontmatter` falls through to `GetString`. +- `pkg/storage/base.go` — `storage.ParseFrontmatterMap(ctx, content []byte) (map[string]any, error)` is exported. Its `frontmatterRegex` is `(?s)^---\n(.*?)\n---\n(.*)$`: it requires a leading `---\n` with **no BOM and no CRLF**, which is exactly why the gate normalises the document first. `storage.CheckboxRegex` is `^(\s*)[-*] \[([ x/])\] (.+)$` — do not reuse it (requirement 1.5). +- `pkg/storage/errors.go` — `storage.ErrNotFound`; test with `errors.Is` from `github.com/bborbe/errors`. +- `scripts/update-topic-goal-entries.awk` — the shipped, tested level-relative `Goals` reader. Port its three properties: level-relative bound, `^- \[\[\]\]` declaration only, and no silent skip. +- `agents/goal-manager-agent.md` line 152 — the in-repo closure-box table by kind: goal = `# Success Criteria` + `# Definition of Done`; topic = `# Success Criteria` + `# Completion Gate`. The section sets in this prompt must agree with it. +- `agents/topic-manager-agent.md` line 67 — the level-relative `## Goals` bound statement: `## Goals` runs past `###` sub-headings and ends at the next `#` or `##`; `# Goals` ends at the next `#`. +- `pkg/cli/cli.go` — `runMutation` (line 115) prints the `MutationResult` as JSON when `--output json` and otherwise returns the error; `Execute` (line 3301) prints `Error: ` to stderr and exits 1. `createGoalCompleteCommand` (1471-1532) and `createTopicCompleteCommand` (1797-1835) are the two call sites; `NewGoalCompleteOperation` is constructed at 1501, `NewTopicCompleteOperation` at 1822. +- `pkg/cli/output.go` — `OutputFormat`, `PrintJSON`. +- `integration/cli_test.go` — `TestIntegration` entry point is in `integration/integration_suite_test.go`; `binPath` is built by `gexec.Build`. Helpers: `createTempVaultWithGoals(tasks, goals)` (line 47) and `createTempVaultWithTopicPages(topicsDir, topics, goals)` (line 188). Existing complete cases that will break without a fixture update: the `Describe("vault-cli goal close-out gating")` fixture (line ~2085), the `Describe("vault-cli goal terminal phase")` fixture (line ~2197), and `It("topic complete moves the status to completed and refuses a second complete")` (line 6161). `sha256OfFile` is declared as a local closure in several Describe blocks — declare your own in each new block. + +Coding-plugin docs (in-container paths): +- `/home/node/.claude/plugins/marketplaces/coding/docs/go-testing-guide.md` — Ginkgo v2/Gomega, external `_test` packages, `DescribeTable`. +- `/home/node/.claude/plugins/marketplaces/coding/docs/go-error-wrapping-guide.md` — `github.com/bborbe/errors`, never `fmt.Errorf`, never `context.Background()`. +- `/home/node/.claude/plugins/marketplaces/coding/docs/go-patterns.md` — exported doc comments, Interface → Constructor → Struct. +- `/home/node/.claude/plugins/marketplaces/coding/docs/go-precommit.md` — funlen 80 lines / 50 statements, nestif 4, gocognit 20, maintidx 20, dupl. +- `/home/node/.claude/plugins/marketplaces/coding/docs/definition-of-done.md` — coverage and verification. + + + +## 1. New file `pkg/ops/closure_gate.go` + +BSD license header `// Copyright (c) 2026 Benjamin Borbe All rights reserved.` and the standard two following lines, `package ops`. Imports: `context`, `fmt`, `regexp`, `strings`, `github.com/bborbe/errors`, `github.com/bborbe/vault-cli/pkg/domain`, `github.com/bborbe/vault-cli/pkg/storage`. It must not import `pkg/cli`, must not write to stdout/stderr, and must never write, create or delete a file. + +### 1.1 Types and constants + +```go +// closureKind selects the section set a closure gate reads. +type closureKind string + +const ( + // closureKindGoal gates a goal on Success Criteria + Definition of Done. + closureKindGoal closureKind = "goal" + // closureKindTopic gates a topic on Success Criteria + Completion Gate. + closureKindTopic closureKind = "topic" +) + +// closureOutcome is the verdict of a closure gate. +type closureOutcome string + +const ( + // closureOutcomeOpen means the page is measurable and at least one box or member is open. + closureOutcomeOpen closureOutcome = "OPEN" + // closureOutcomeUnmeasurable means the page's evidence cannot be read at all. + closureOutcomeUnmeasurable closureOutcome = "UNMEASURABLE" + // closureOutcomeClose means every box is ticked and every member is terminal. + closureOutcomeClose closureOutcome = "CLOSE" + // closureOutcomeTerminal means the page is already completed or aborted. + closureOutcomeTerminal closureOutcome = "TERMINAL" +) + +// closureMember is a linked task (goal kind) or a member goal (topic kind). +// Fields are exported so the external ops_test package can build values. +type closureMember struct { + Name string + Status string +} + +// closureVerdict is the result of checkClosureGate. +type closureVerdict struct { + Outcome closureOutcome + OpenItems []string +} + +// dodRequiredAsOf is the grandfathering cutoff. It is the fourth copy of the +// value: claude-supervisor/scripts/goal-closure-read.py, agents/goal-auditor.md +// and agents/task-auditor.md carry the other three. They move together. +const dodRequiredAsOf = "2026-06-26" +``` + +### 1.2 The shared check + +```go +// checkClosureGate reads the page's own closure evidence and returns a verdict. +// It is the single implementation behind both `goal complete` and +// `topic complete`; neither verb may carry a second copy of the rule. +// +// The section set is fixed by kind, never guessed from the page: +// goal -> "# Success Criteria" + "# Definition of Done"; +// topic -> "# Success Criteria" + "# Completion Gate". +// +// The check is read-only. A page already at completed/aborted returns TERMINAL +// with no items. On any refusal OpenItems holds one human-readable string per +// blocking item, in document order (sections first, then members). +func checkClosureGate( + ctx context.Context, + kind closureKind, + content string, + members []closureMember, +) (closureVerdict, error) +``` + +Evaluation order, exactly: + +1. `doc := normaliseDocument(content)`. +2. `fields, err := storage.ParseFrontmatterMap(ctx, []byte(doc))`; on error return `closureVerdict{}` and `errors.Wrap(ctx, err, "parse frontmatter")`. A page whose frontmatter does not parse is never grandfathered. +3. Read `status` from `fields` with a `string` type switch (a non-string value reads as `""`). If it is `completed` or `aborted`, return `{Outcome: closureOutcomeTerminal}` immediately, with no items and no section scan. +4. `body, err := stripFrontmatter(ctx, doc)`; on error return `closureVerdict{}` and the error. +5. `body, fenceOK := stripFencedBlocks(body)`. If `!fenceOK`, return `{Outcome: closureOutcomeUnmeasurable, OpenItems: []string{"unterminated code fence"}}` — the fence makes every later section unreadable, so nothing else is evaluated. +6. `created` is read from `fields` the same way as `status`. +7. Walk the kind's section set in the fixed order `["# Success Criteria", "# Definition of Done"]` for goals and `["# Success Criteria", "# Completion Gate"]` for topics: + - `lines, found := findSection(body, heading)`. + - **Absent:** add the item `": section absent"`, except the goal-only grandfathering case in 1.4. + - **Present:** run the section's own check (1.5 / 1.6). +8. Walk `members`. For each member the kind considers open, append `" ()"`; when `Status == ""` append just `""`. Goal members are open when the status is one of `next`, `todo`, `in_progress` (unchanged from today); every other goal-member status is terminal. Topic members are open when the status is neither `completed` nor `aborted`. Empty member statuses are always open. +9. Outcome: if any item came from an unmeasurable condition (absent section, section with zero checkboxes, strict Completion Gate violation, unterminated fence) return `closureOutcomeUnmeasurable`; else if any item is an open box or open member return `closureOutcomeOpen`; else return `closureOutcomeClose`. `UNMEASURABLE` outranks `OPEN`. The returned `OpenItems` is the full list either way, in the order produced above. + +### 1.3 Normalisation and section location + +- `normaliseDocument(content string) string`: strip one leading UTF-8 BOM (the three-byte sequence written `"\ufeff"`), replace `"\r\n"` with `"\n"`, then replace any remaining `"\r"` with `"\n"`. This is what makes `frontmatterRegex`'s `^---\n` match a CRLF or BOM page. +- `stripFrontmatter(ctx context.Context, doc string) (string, error)`: `doc` is already normalised and its frontmatter already parsed, so it starts with `"---\n"`. Return the body after the closing `"\n---\n"`. When the closing delimiter is missing, return `errors.Errorf(ctx, "frontmatter block not found")` — never `fmt.Errorf`. Callers only reach this after a successful parse, so this is defensive. +- `stripFencedBlocks(body string) (string, bool)`: walk lines; outside a fence, a line whose left-trimmed form starts with three backticks or three tildes opens a fence (remember which character) and is dropped; inside a fence, a line whose left-trimmed form starts with three of the opening character closes it and is dropped; every other in-fence line is dropped. Return the remaining lines joined with `"\n"`, and `false` when the document ends inside a fence. A checkbox inside a fence is never a box. +- `findSection(body, heading string) ([]string, bool)`: `heading` is `"# Success Criteria"`, `"# Definition of Done"` or `"# Completion Gate"` — level 1 and exact text after trimming trailing spaces. The section body runs from the line after the heading to the next level-1 heading (exclusive) or end of document. Subsections (`##`, `###`) are part of the body and their boxes count. +- `headingLevel(line string) int`: 1-6 from a leading `#` run followed by a space or tab, else 0. Define the regex locally; `storage.parseMarkdownHeading` is unexported and must not be reached for. +- `hasDoDShapedHeading(body string) bool`: true when **any** line, after trimming leading whitespace, leading `#` characters and a leading `-`/`*`/`+` list marker (plus following whitespace), equals `Definition of Done`. This catches `# Definition of Done`, `## Definition of Done`, a setext heading's text line, and `- Definition of Done`. The grandfathering exemption is skipped entirely when this is true. + +### 1.4 Grandfathering (goals only, absence only) + +Only when `kind == closureKindGoal` and the `# Definition of Done` section is absent: + +- Skip the exemption when `hasDoDShapedHeading(body)` is true — add `"# Definition of Done: section absent"` and treat it as unmeasurable. +- `created == ""` → grandfathered. +- `created` matching `^\d{4}-\d{2}-\d{2}$` and lexicographically earlier than `dodRequiredAsOf` → grandfathered. +- Any other `created` (non-ISO, e.g. `15.01.2026`, `2026`) → not grandfathered; add `"# Definition of Done: section absent (created \"\" is not an ISO date)"` and treat it as unmeasurable. +- `created` on or after the cutoff → not grandfathered; add `"# Definition of Done: section absent (created is not before )"`. +- A **present** DoD heading with zero boxes is never grandfathered: it is unmeasurable, always. +- Grandfathering never applies to `topic`. + +### 1.5 Checkbox rules + +Define package-level compiled regexes (package-level vars are the pattern `pkg/storage/base.go` already uses): + +```go +// closureCheckboxRegex matches a checkbox item with any bullet marker and any +// single-character marker. Capture 1 is the marker, 2 the item text. +var closureCheckboxRegex = regexp.MustCompile(`^[ \t]*[-*+][ \t]+\[(.)\][ \t]*(.*)$`) + +// closureListItemRegex matches any markdown list item, checkbox or not. +var closureListItemRegex = regexp.MustCompile(`^[ \t]*([-*+]|\d+\.)[ \t]+`) +``` + +- `sectionCheckboxItems(lines []string) (open []string, total int)`: for each line matching `closureCheckboxRegex`, `total++`; the marker `x` or `X` is done, **every** other marker (` `, `/`, `-`, `?`, anything) is open and contributes the trimmed capture 2 as an item, or the trimmed raw line when capture 2 is empty. Do **not** use `storage.CheckboxRegex` — it accepts only `-`/`*` and only three markers, and it would silently treat `- [+] item` as a non-checkbox. +- A section present with `total == 0` adds `": section contains no checkbox"` and is unmeasurable. An empty section is never vacuously complete. + +### 1.6 Strict Completion Gate + +For the topic's `# Completion Gate` only: after collecting its checkboxes, scan the same lines with `closureListItemRegex`. Any matching line that is **not** a checkbox (does not match `closureCheckboxRegex`) is a violation: add `"# Completion Gate: non-checkbox list item: "` and mark the section unmeasurable. This includes ordered-list items (`1. ...`). Do not apply this strictness to `# Success Criteria` or `# Definition of Done`. + +### 1.7 Goals-section member reader + +```go +// parseGoalSectionMembers returns the goal names declared in a topic page's +// Goals section, bounded level-relative. +func parseGoalSectionMembers(content string) []string +``` + +- Normalise and strip frontmatter as above (tolerate a missing frontmatter block by using the whole normalised document — this reader must not fail a page the gate will judge separately). Strip fenced blocks; on an unterminated fence return `nil`. +- Find a heading whose trimmed text is exactly `Goals` at level 1 or 2 (`# Goals` or `## Goals`). Ignore `### Goals` and deeper. If absent, return `nil`. +- The section ends at the next heading whose level is **less than or equal to the Goals heading's own level**. `## Goals` therefore runs past `###` sub-headings; `# Goals` ends at the next `#`. This bound is load-bearing (spec DB12): bounding at any heading, or at `##` only, under-reads members and lets an incomplete topic close. +- An entry is a line matching `^- \[\[([^\]|#]+)\]\]` at column 0 — a declaration, not a mention. Strip a trailing `|alias` and `#heading` from the captured name (do this in the capture or immediately after; `storage.findFileByName` does not strip them). Numbered list items, bold prose lines and mid-sentence wikilinks are not entries. +- Return names in document order, de-duplicated on first occurrence. + +### 1.8 Refusal message + +```go +// closureRefusalMessage builds the single-line error text for a refusal. +func closureRefusalMessage(subject string, items []string) string +``` + +Returns `fmt.Sprintf("cannot complete %s: %d closure item(s) open: %s", subject, len(items), strings.Join(items, "; "))`. `subject` is `"goal"` or `"topic"`. Existing unit tests assert `"cannot complete goal"` and the member name appear in `err.Error()`, so the item text must be embedded. + +Keep every function in this file under 80 lines / 50 statements with `nestif` below 4. Split the section walk into a helper if needed (e.g. `closureSectionItems`); do not reach for `//nolint:funlen`. + +## 2. `MutationResult` gains `OpenItems` + +In `pkg/ops/complete.go`, add to `MutationResult` after `Total`: + +```go + // OpenItems lists every closure item that blocks a goal or topic close, in + // document order. Populated only on a closure-gate refusal. + OpenItems []string `json:"open_items,omitempty"` +``` + +`checkSubtaskCompletion`, `countCheckboxStates`, `resetCheckboxes` and every task path stay untouched. + +## 3. Wire `goal complete` + +In `pkg/ops/goal_complete.go`: + +1. Replace the `already completed` branch (lines 73-76) with a terminal no-op. Use the already-parsed page status, so a terminal page does not list tasks: + ```go + if goal.Status() == domain.GoalStatusCompleted || goal.Status() == domain.GoalStatusAborted { + return MutationResult{Success: true, Name: goal.Name, Vault: vaultName}, nil + } + ``` + After this rewrite nothing else in `goal_complete.go` uses `fmt` or `strings` (they were used only by the removed refusal message and `joinTaskNames`); remove both imports if the compiler reports them unused. +2. Replace `checkOpenTasks` with a member collector that keeps the same filtering and formatting: + ```go + // linkedTaskMembers returns every task linked to the goal, as closure members. + // It is the only reader of the task relation; the gate decides which statuses + // are open. + func (g *goalCompleteOperation) linkedTaskMembers( + ctx context.Context, + vaultPath string, + goalName string, + ) ([]closureMember, error) + ``` + `ListTasks`; for each task with `taskLinkedToGoal(task, goalName)` append `closureMember{Name: task.Name, Status: string(task.Status())}`. Do not filter by status here — the gate applies the open-status set. On `ListTasks` error return `errors.Wrap(ctx, err, "list tasks")`. Delete `joinTaskNames` if nothing else uses it (grep first); keep `checkOpenTasks`'s existing message assertions satisfied through `closureRefusalMessage` (requirement 1.8). +3. In `Execute`, after the terminal no-op and before any status mutation: + ```go + var members []closureMember + if !force { + members, err = g.linkedTaskMembers(ctx, vaultPath, goalName) + if err != nil { + return MutationResult{Success: false, Error: err.Error()}, err + } + } + verdict, err := checkClosureGate(ctx, closureKindGoal, string(goal.Content), members) + if err != nil { + return MutationResult{Success: false, Error: err.Error()}, err + } + if verdict.Outcome == closureOutcomeTerminal { + return MutationResult{Success: true, Name: goal.Name, Vault: vaultName}, nil + } + if verdict.Outcome != closureOutcomeClose { + msg := closureRefusalMessage("goal", verdict.OpenItems) + return MutationResult{Success: false, Error: msg, OpenItems: verdict.OpenItems}, + errors.Errorf(ctx, "%s", msg) + } + ``` + `force` therefore bypasses **only** the member list, never the section gate: a forced close still refuses on an open criterion. +4. `taskLinkedToGoal` normalises both link forms: + ```go + func taskLinkedToGoal(task *domain.Task, goalName string) bool { + for _, g := range task.Goals() { + if normaliseGoalLink(g) == goalName { + return true + } + } + return false + } + + // normaliseGoalLink strips the wikilink wrapper and any alias/heading suffix + // so '[[Some Goal]]', '[[Some Goal|label]]' and 'Some Goal' compare equal. + func normaliseGoalLink(link string) string + ``` + Trim surrounding whitespace; strip one leading `[[` and one trailing `]]`; strip everything from the first `|`; strip everything from the first `#`. Leave the open-status set (`next`, `todo`, `in_progress`) unchanged — it now lives in the gate, not in this function. + +`checkClosureGate` must appear **exactly once** in this file (the call above). Do not mention it in a comment here. + +## 4. Wire `topic complete` + +In `pkg/ops/topic_complete.go`: + +1. Constructor gains goal storage: + ```go + func NewTopicCompleteOperation( + topicStorage storage.TopicStorage, + goalStorage storage.GoalStorage, + ) TopicCompleteOperation + ``` + Add the field and doc-comment the reason: the member-goal terminality check needs each member's status, and topics carry no task relation. Update the `Execute` doc comment, which currently says "there is no open-task gate" — it now has a closure gate. +2. Replace the `already completed` branch (lines 52-55) with: + ```go + if status := topic.GetField("status"); status == domain.TopicStatusCompleted || status == "aborted" { + return MutationResult{Success: true, Name: topic.Name, Vault: vaultName}, nil + } + ``` +3. Before `SetField`, build members and run the gate: + ```go + members, err := o.goalMembers(ctx, vaultPath, string(topic.Content)) + if err != nil { + return MutationResult{Success: false, Error: err.Error()}, err + } + verdict, err := checkClosureGate(ctx, closureKindTopic, string(topic.Content), members) + if err != nil { + return MutationResult{Success: false, Error: err.Error()}, err + } + if verdict.Outcome == closureOutcomeTerminal { + return MutationResult{Success: true, Name: topic.Name, Vault: vaultName}, nil + } + if verdict.Outcome != closureOutcomeClose { + msg := closureRefusalMessage("topic", verdict.OpenItems) + return MutationResult{Success: false, Error: msg, OpenItems: verdict.OpenItems}, + errors.Errorf(ctx, "%s", msg) + } + ``` + ```go + // goalMembers resolves each goal named in the topic's Goals section to its + // status. A member whose goal file does not exist reads as open (Status ""): + // an unresolvable member is never treated as terminal. + func (o *topicCompleteOperation) goalMembers( + ctx context.Context, + vaultPath string, + content string, + ) ([]closureMember, error) + ``` + For each name from `parseGoalSectionMembers(content)`: `goalStorage.FindGoalByName(ctx, vaultPath, name)`; on `errors.Is(err, storage.ErrNotFound)` append `closureMember{Name: name}` and continue; on any other error return `errors.Wrapf(ctx, err, "find goal %s", name)`. Otherwise append `closureMember{Name: name, Status: string(goal.Status())}`. +4. Do **not** add a `--force` flag, a `reason` or a `gateSuccessor` parameter. + +Update the one production call site in `pkg/cli/cli.go` (line 1822): + +```go +goalStore := storage.NewGoalStorage(storageConfig) +completeOp := ops.NewTopicCompleteOperation(topicStore, goalStore) +``` + +`grep -rn 'NewTopicCompleteOperation' .` afterwards must show only `pkg/cli/cli.go`, `pkg/ops/topic_complete.go` and `pkg/ops/topic_complete_test.go`. + +## 5. CLI: print one line per open item + +In `pkg/cli/cli.go`, add next to `runMutation`: + +```go +// printOpenItems writes one stdout line per closure-gate item. A refusal must +// name what is open on stdout; the error itself goes to stderr via Execute. +func printOpenItems(items []string) { + for _, item := range items { + fmt.Println(item) + } +} +``` + +In `createGoalCompleteCommand`'s runner and `createTopicCompleteCommand`'s runner, replace the plain `if err != nil { return result, err }` with: + +```go +if err != nil { + if !OutputFormat(*outputFormat).IsJSON() { + printOpenItems(result.OpenItems) + } + return result, err +} +``` + +The success lines (`✅ Goal completed: …`, `✅ Topic completed: …`) stay as they are and are printed only on success. `runMutation` already prints the result as JSON on error, so `--output json` surfaces `open_items` with no further change. A refusal exits 1 via `cli.Execute`; nothing else is written to stdout. + +If `dupl` reports the two runners as duplicates, add `//nolint:dupl // Mutation commands have similar structure but different operations` above the function, matching the existing comments in this file. Do not refactor unrelated commands. + +## 6. Tests + +### 6.1 Expose the gate to `ops_test` + +Append to `pkg/ops/export_test.go` (same style as the existing aliases): + +```go +// CheckClosureGate exposes checkClosureGate for the external ops_test package. +var CheckClosureGate = checkClosureGate + +// ParseGoalSectionMembers exposes parseGoalSectionMembers for ops_test. +var ParseGoalSectionMembers = parseGoalSectionMembers + +// Closure kinds and outcomes for ops_test. +const ( + ClosureKindGoal = closureKindGoal + ClosureKindTopic = closureKindTopic + ClosureOutcomeOpen = closureOutcomeOpen + ClosureOutcomeUnmeasurable = closureOutcomeUnmeasurable + ClosureOutcomeClose = closureOutcomeClose + ClosureOutcomeTerminal = closureOutcomeTerminal +) + +// ClosureMember and ClosureVerdict expose the gate's value types to ops_test. +type ClosureMember = closureMember + +type ClosureVerdict = closureVerdict +``` + +The `closureMember` / `closureVerdict` fields are already exported, so the aliases are constructible from `ops_test`. + +### 6.2 New file `pkg/ops/closure_gate_test.go` (package `ops_test`) + +One `Describe("Closure gate", …)` containing a single `DescribeTable("verdict", …)` (or one table per kind — the focus must still match every entry). Each entry calls `ops.CheckClosureGate(ctx, kind, content, members)` and asserts **both** `verdict.Outcome` and the expected `OpenItems` count/content. A case that only runs is not evidence. + +Required entries, each asserting its own expected verdict: + +| Entry name | Kind | Fixture | Expected | +|---|---|---|---| +| `SC box open` | goal | full frontmatter, `# Success Criteria` with `- [ ] an open criterion`, `# Definition of Done` all `[x]` | `OPEN`, 1 item containing `an open criterion` | +| `DoD section present but empty` | goal | SC all `[x]`, `# Definition of Done` heading with no box | `UNMEASURABLE`, 1 item naming `# Definition of Done` | +| `DoD absent before cutoff is grandfathered` | goal | `created: "2026-06-01"`, no DoD heading, SC all `[x]` | `CLOSE`, 0 items | +| `DoD absent with no created is grandfathered` | goal | no `created`, no DoD heading, SC all `[x]` | `CLOSE`, 0 items | +| `DoD heading in a non-# spelling is unmeasurable` | goal | `created: "2026-06-01"`, `## Definition of Done` with no box | `UNMEASURABLE`, not grandfathered | +| `DoD heading as a bullet is unmeasurable` | goal | `created: "2026-06-01"`, `- Definition of Done` with no box | `UNMEASURABLE`, not grandfathered | +| `DoD heading as setext is unmeasurable` | goal | `created: "2026-06-01"`, `Definition of Done` followed by `===` and no box | `UNMEASURABLE`, not grandfathered | +| `DoD absent on or after cutoff` | goal | `created: "2026-06-26"`, no DoD heading, SC all `[x]` | `UNMEASURABLE`, 1 item naming `# Definition of Done` | +| `DoD absent with non-ISO created` | goal | `created: "15.01.2026"`, no DoD heading, SC all `[x]` | `UNMEASURABLE`, 1 item naming `# Definition of Done` | +| `star bullet open box` | goal | `# Success Criteria` with `* [ ] open`, DoD all `[x]` | `OPEN` | +| `unrecognised dash marker` | goal | `# Success Criteria` with `- [-] open`, DoD all `[x]` | `OPEN` | +| `unrecognised question marker` | goal | `# Success Criteria` with `- [?] open`, DoD all `[x]` | `OPEN` | +| `box inside fenced block is not a box` | goal | SC holding only a fenced `- [ ] example`, DoD all `[x]` | `UNMEASURABLE`, 1 item naming `# Success Criteria` | +| `unterminated fence` | goal | document ending inside a fence | `UNMEASURABLE`, exactly 1 item `unterminated code fence` | +| `BOM prefixed CRLF page` | goal | content prefixed with `"\ufeff"` and using `"\r\n"` line endings, `created` before cutoff, SC all `[x]` | `CLOSE` (frontmatter read) | +| `Completion Gate box open` | topic | SC all `[x]`, `# Completion Gate` with `- [ ] gate` | `OPEN`, 1 item `gate` | +| `Completion Gate mixes a checkbox with an ordered item` | topic | SC all `[x]`, `# Completion Gate` with `- [x] done` and `1. an ordered item` | `UNMEASURABLE` | +| `member goal not terminal` | topic | complete SC + Gate, member `{Name: "member", Status: "in_progress"}` | `OPEN`, item naming `member` | +| `member goal terminal` | topic | complete SC + Gate, member `{Name: "member", Status: "completed"}` | `CLOSE` | +| `topic with no Goals section` | topic | complete SC + Gate, no Goals heading, no members | `CLOSE` | +| `already completed page` | goal | `status: completed` | `TERMINAL`, 0 items | +| `already aborted page` | goal | `status: aborted` | `TERMINAL`, 0 items | +| `missing frontmatter` | goal | content with no frontmatter | an error (assert `err` is not nil) | + +Add a second `Describe("Closure gate Goals section", …)` with a `DescribeTable("members", …)` covering `parseGoalSectionMembers`: +- `## Goals` with `- [[A]]` and `- [[B]]` → `[A B]`; +- `## Goals` with a `### Lever A` sub-heading holding `- [[C]]` → `[A B C]` (bound is level-relative); +- `# Goals` with a `## Sub` sub-heading holding `- [[D]]` → includes `D` (bound is not fixed at `##`); +- `# Goals` followed by a second `# Other` heading whose body holds `- [[E]]` → `E` excluded; +- a numbered `1. [[X]]`, a bold `**[[Y]]**` line and a mid-sentence wikilink → none included; +- `- [[Name|label]]` → `Name`; +- no Goals heading → empty. + +### 6.3 Repair `pkg/ops/goal_complete_test.go` + +- Add a package-level helper in the test file (or a `BeforeEach` default) producing a closure-complete goal body: + ```go + func completeGoalContent(status string) domain.Content { + return domain.Content("---\nstatus: " + status + "\n---\n# Success Criteria\n- [x] done\n") + } + ``` + The absent `# Definition of Done` is grandfathered (no `created`), so this body closes. +- Replace every fixture that expects a successful close (`Content("")` on a goal expected to complete: the default `BeforeEach`, "goal completes without close-out fields", "one-step close-out…", both phase contexts, "success", "completed tasks do not block", "tasks linked to other goals do not block", "zero linked tasks", "force bypasses open task check") with `completeGoalContent()`. Do not weaken any assertion. +- **Invert** `Context("goal already completed")` (lines 88-101): keep the context, keep the two `It`s but change them to assert `err` is nil, `result.Success` is true, `result.Name` equals `goalName`, and `WriteGoalCallCount()` is 0. Add a third `It` asserting `result.OpenItems` is empty. Do not delete the context. +- Add `Context("goal already aborted")` mirroring the inverted completed context (status `aborted`). +- Add `Context("force does not bypass an open criterion")`: `force = true`, content with an open SC box and a DoD all ticked; assert error, `WriteGoalCallCount() == 0`, and `result.OpenItems` contains the criterion text. +- Add `Context("bracketed goal link blocks completion")`: a task named `linked-task` at `status: todo` whose `SetGoals([]string{"[[" + goalName + "]]"})`; assert the error contains `linked-task` and no write. Add the bare-name twin (`SetGoals([]string{goalName})`) asserting the same, so the asymmetry is pinned. Also add two suffix cases, each asserting the refusal still fires and no write happens: `SetGoals([]string{"[[" + goalName + "|label]]"})` and `SetGoals([]string{"[[" + goalName + "#heading]]"})` — these pin `normaliseGoalLink`'s alias and heading stripping, which nothing else exercises. +- Add `Context("open criterion blocks completion")`: content with one open SC box and a ticked DoD; assert error containing the criterion text, `WriteGoalCallCount() == 0`, and `result.OpenItems` length 1. +- Keep the existing "open todo task blocks completion" / "open in_progress task blocks completion" contexts working: their error text now comes from `closureRefusalMessage`, and it still contains `cannot complete goal` and the task name. + +### 6.4 Repair `pkg/ops/topic_complete_test.go` + +- Add `mockGoalStorage *mocks.GoalStorage` and construct with `ops.NewTopicCompleteOperation(mockTopicStorage, mockGoalStorage)`. The file will need the imports `"github.com/bborbe/errors"` (for `errors.Is`) and `"github.com/bborbe/vault-cli/pkg/storage"` (for `storage.ErrNotFound`). +- Add a closure-complete topic body helper: + ```go + func completeTopicContent(status string) domain.Content { + return domain.Content("---\nstatus: " + status + "\n---\n# Success Criteria\n- [x] done\n# Completion Gate\n- [x] gated\n") + } + ``` +- Use it for the default `BeforeEach` (line 42) and both alternate fixtures (lines 90, 108). +- **Invert** `Context("topic already completed")` (lines 121-144): assert `err` is nil, `result.Success` is true, `WriteTopicCallCount() == 0`. Do not delete the context. +- Add `Context("topic already aborted")` mirroring it. +- Add `Context("open Completion Gate box blocks completion")` and `Context("non-terminal member goal blocks completion")` (member `my-member` at `in_progress`, `mockGoalStorage.FindGoalByNameReturns(goal, nil)` for that name; assert the error names the member and no write). +- Add `Context("member goal missing from the vault blocks completion")`: `FindGoalByNameReturns(nil, storage.ErrNotFound)`; assert error and no write. +- Existing "topic not found" and "write topic fails" contexts stay unchanged. + +### 6.5 Integration tests in `integration/cli_test.go` + +Add a new `Describe("vault-cli goal and topic closure gate", …)` block (or two sibling blocks — goal and topic) after the existing `Describe("vault-cli goal terminal phase")` block. Each `It` gets its own temp vault via `createTempVaultWithGoals` / `createTempVaultWithTopicPages`, a `runCommand(args ...string) *gexec.Session` closure, a `readFile` closure, and its own `sha256OfFile` closure (copy the existing local-closure style; do not add a package-level helper). + +Case names and assertions (every name must appear in `go test ./integration -run TestIntegration -ginkgo.v -v`): + +1. `It("goal complete refuses an open Success Criteria box and leaves status in_progress")` — goal fixture with one open SC box and a ticked DoD; `goal complete` exits non-zero, stdout contains the box text, and the on-disk file still reads `status: in_progress`. +2. `It("goal complete closes a fully ticked goal with terminal linked tasks")` — every SC and DoD box `[x]`, one linked task at `completed`; exit 0, file reads `status: completed`. +3. `It("goal complete refuses an open task linked as a wikilink")` — task `goals: ["[[]]"]` at `todo`; non-zero exit, stdout contains the task name, file unchanged. +4. `It("goal complete refuses an open task linked as a bare name")` — same task with the bare name; non-zero exit, stdout contains the task name. +5. `It("goal complete closes a pre-cutoff goal with no Definition of Done")` — `created: "2026-01-05"`, no DoD section, SC all `[x]`; exit 0, `status: completed`. +6. `It("goal complete refuses a goal whose Definition of Done section holds no box")` — DoD heading present, no box; non-zero exit, stdout names `# Definition of Done`. +7. `It("goal complete refuses a post-cutoff goal with no Definition of Done")` — `created: "2026-07-01"`, no DoD; non-zero exit, stdout names `# Definition of Done`. +8. `It("topic complete refuses an open Completion Gate box")` — SC all `[x]`, open Gate box; non-zero exit, stdout contains the gate text, file still `in_progress`. +9. `It("topic complete refuses a non-terminal member goal")` — complete SC + Gate, `## Goals` listing `- [[Member Goal]]`, member goal at `in_progress`; non-zero exit, stdout names `Member Goal`. +10. `It("topic complete reads a member under a ### sub-heading inside ## Goals")` — SC and Gate all `[x]`, member declared under `### Lever A` inside `## Goals`, member at `in_progress`; non-zero exit naming the member (proves the bound is not "any heading"). +11. `It("topic complete reads a member under ## inside # Goals")` — SC and Gate all `[x]`, `# Goals` with a `## Sub` sub-heading holding the non-terminal member; non-zero exit naming the member (proves the bound is level-relative, not fixed at `##`). +12. `It("topic complete closes a fully ticked topic with terminal member goals")` — SC and Gate all `[x]`, member goal `completed`; exit 0, `status: completed`. +13. `It("goal complete prints one line per open item and reports them in open_items")` — goal with exactly two open SC boxes. Run the plain invocation: exit non-zero, and `strings.Split(strings.TrimSpace(string(session.Out.Contents())), "\n")` has length 2. Run the same command with `--output json`: exit non-zero, unmarshal stdout into `map[string]any`, assert `open_items` is a `[]any` of length 2. Do not depend on `jq` being installed; the JSON probe is the Go unmarshal. +14. `It("goal complete is a no-op on an already-completed goal")` — fixture `status: completed`; capture the digest, run, exit 0, digest unchanged. +15. `It("goal complete is a no-op on an aborted goal")` — fixture `status: aborted`; exit 0, digest unchanged. +16. `It("topic complete is a no-op on an aborted topic")` — topic `status: aborted`; exit 0, digest unchanged. + +Additionally **rewrite** the existing `It("topic complete moves the status to completed and refuses a second complete")` (line 6161) into `It("topic complete moves the status to completed and is a no-op on a second complete")`: give the fixture a closure-complete body, keep the first-command assertions (`status: completed`), then assert the second command exits **0** and the file digest is unchanged. That is the fourth terminal digest case. + +Repair the two existing fixtures that feed a successful `goal complete`: +- `Describe("vault-cli goal close-out gating")` fixture (line ~2085): change the `my-goal` body to `---\nstatus: in_progress\n---\n# My Goal\n# Success Criteria\n- [x] done\n`. +- `Describe("vault-cli goal terminal phase")` fixture (line ~2197): same body, keeping `phase: execution`. +No other existing integration assertion may be relaxed or deleted. + +## 7. CHANGELOG + +`CHANGELOG.md` has no `## Unreleased` section. Create it **below** the preamble block (after the `* PATCH version …` line) and **above** `## v0.197.1`, with one bullet: + +``` +## Unreleased + +- fix: `goal complete` and `topic complete` refuse to close a page whose own closure evidence is incomplete, name every open item on stdout and in `--output json` under `open_items`, and treat an already-completed or aborted page as a no-op instead of an error +``` + +Do not bump any version manifest and do not tag. + + + +- **Do not change `task complete`'s behaviour.** `pkg/ops/complete.go`'s `checkSubtaskCompletion`, `countCheckboxStates` and `resetCheckboxes` are the model, not a target. The only edit to that file is the `OpenItems` field on `MutationResult`. +- **Do not shell out to, import, or depend on `claude-supervisor`.** The two plugins are installed independently; vault-cli must work when the other is absent. Do not read `goal-closure-read.py` at runtime. +- **The check is read-only.** `checkClosureGate`, `parseGoalSectionMembers` and their helpers never write, create or delete a file. +- **`pkg/ops` is a library layer** — it returns structured results and never writes to stdout. All output formatting lives in `pkg/cli`. +- **The JSON field is `open_items`**, a `[]string` on `MutationResult`, with tag `json:"open_items,omitempty"`. Do not invent another name. +- **Invert, do not delete, the two existing terminal tests** (`pkg/ops/goal_complete_test.go:88-101`, `pkg/ops/topic_complete_test.go:121-144`). +- **`--force` on `goal complete` bypasses only the open-task gate**, never the closure gate. `topic complete` gains no `--force`, no `--reason`, no `--gate-successor`. +- **`checkClosureGate` appears exactly once in `pkg/ops/goal_complete.go` and exactly once in `pkg/ops/topic_complete.go`** — the call site. The definition lives in `pkg/ops/closure_gate.go`. Do not mention the name in comments in those two files. +- **No checkbox regex in the two call-site files.** `grep -cE '\[[ xX/-]\]' pkg/ops/goal_complete.go pkg/ops/topic_complete.go` must return 0 for each; the regex lives only in `pkg/ops/closure_gate.go`. +- **Do not touch** `pkg/ops/objective_complete.go`, `theme complete`, `vision complete`, `goal set`, `topic set`, `task set`, or any lint rule. +- **Do not retrofit historical pages.** No migration, no bulk rewrite, no backfill of `created`. +- **Do not edit** `agents/*.md`, `docs/*.md`, `scripts/*.sh`, `commands/*.md`, or the vault's closure guide. The in-repo closure-box table (`agents/goal-manager-agent.md` line 152) is a reference to agree with, not a file to change. +- **Error wrapping** goes through `github.com/bborbe/errors` — `errors.Wrap`, `errors.Wrapf`, `errors.Errorf` with `ctx`. Never `fmt.Errorf`, never `context.Background()` inside `pkg/ops`. +- **Do not hand-bump version manifests or tag.** `.dark-factory.yaml` carries `autoRelease: false` for the container run; the releaser owns the tag post-merge. +- Do NOT commit — dark-factory handles git. +- Existing tests must still pass. + + + +Run `make test` — must exit 0. Re-run it iteratively while implementing; it is the fast feedback loop. + +Focused runs (confirm the new case names actually appear — a focus matching zero specs exits 0 while running nothing): + +``` +go test -mod=mod ./pkg/ops -run TestSuite -ginkgo.focus=Closure -ginkgo.v +go test -mod=mod ./integration -run TestIntegration -ginkgo.v -v +go test -mod=mod ./integration -run TestIntegration -v +``` + +`go test -mod=mod ./integration -run TestIntegration -v` alone may not list spec names under Ginkgo v2's default reporter; the `-ginkgo.v` run is the one that prints them. Both must exit 0, and the `-ginkgo.v` output must contain every case name listed in requirement 6.5 and every table entry name in requirement 6.2. + +Evidence greps (each count is exact unless stated): + +``` +grep -n 'checkClosureGate' pkg/ops/goal_complete.go pkg/ops/topic_complete.go # exactly one line per file +grep -cE '\[[ xX/-]\]' pkg/ops/goal_complete.go # 0 +grep -cE '\[[ xX/-]\]' pkg/ops/topic_complete.go # 0 +grep -c 'open_items' pkg/ops/complete.go # 1 +grep -c 'func checkClosureGate' pkg/ops/closure_gate.go # 1 +grep -rn 'NewTopicCompleteOperation' pkg/ integration/ # cli.go, topic_complete.go, topic_complete_test.go only +grep -n '^## Unreleased' CHANGELOG.md # 1 line, above v0.197.1 +``` + +``` +go vet -mod=mod ./pkg/ops/... ./integration/... ./pkg/cli/... # exits 0 +``` + +Finally run `make precommit` once — must exit 0. + +If `make precommit` exits non-zero: fix, re-run only the failing target (`make lint`, `make test`, `make check-changelog`, …) until it passes, then run `make precommit` once more. A non-zero `make precommit` exit code must be reported as `"status":"failed"` in the completion report — never rationalised as success. + + + diff --git a/specs/in-progress/069-bug-goal-topic-closure-gate.md b/specs/in-progress/069-bug-goal-topic-closure-gate.md new file mode 100644 index 0000000..1238a6b --- /dev/null +++ b/specs/in-progress/069-bug-goal-topic-closure-gate.md @@ -0,0 +1,189 @@ +--- +status: verifying +approved: "2026-11-18T19:46:38Z" +generating: "2026-11-18T22:54:58Z" +verifying: "2026-11-18T23:19:37Z" +branch: dark-factory/bug-goal-topic-closure-gate +--- + +## Summary + +- `vault-cli goal complete` reads no Success Criteria and no Definition of Done. A goal with an open criterion completes and is written `status: completed`. +- Its open-task guard is dead for bracketed links: a task whose `goals:` entry reads `[[Some Goal]]` never matches the goal being closed. +- `vault-cli topic complete` carries no gate at all — neither a Completion Gate check nor a member-goal terminality check. +- The strict gate `vault-cli task complete` already has is the model, and the same closure rule exists in another plugin's reader script but never reaches these two verbs. +- Result: a page whose own evidence is incomplete closes itself, and the vault's "every box must be `[x]`" forcing function does not hold at the goal and topic tiers. + +## Problem + +Every vault tier is supposed to close on its own recorded evidence. A task closes only when no box is open (`pkg/ops/complete.go`, `checkSubtaskCompletion`). A goal is supposed to close only when every `# Success Criteria` and `# Definition of Done` box reads `[x]` **and** no linked task is still open. A topic is supposed to close only when every `# Success Criteria` and `# Completion Gate` box reads `[x]` **and** every member goal is terminal. + +None of the goal/topic half is implemented. `goal_complete.go` inspects linked task statuses and nothing else; `topic_complete.go` inspects nothing. The supervisor's `goal-closure-read.py` computes exactly this verdict, but it is a separate plugin's script — vault-cli cannot call it (the two are independently installed) and currently duplicates none of it. + +Two existing behaviours this change also touches, stated here because the spec changes them: + +- Both verbs **already refuse** an already-`completed` page with a non-zero exit (`goal_complete.go:73-76`, `topic_complete.go:52-55` — `already completed`). This spec turns that into an exit-0 no-op, so a closure loop that re-closes every tick is silent instead of erroring every tick. +- `aborted` is not guarded today at all; it becomes part of the same no-op. + +**Cost of not fixing:** a goal or topic can be closed with open criteria, and the closure is silent — exit 0, a success line, `status: completed` written. Measured 2026-11-18 below. + +## Reproduction + +Environment: `vault-cli version v0.196.0` installed, vault `private-personal`, three scratch pages created for the probe and deleted after it. Code-level claims read at `bborbe/vault-cli@a4fa4de`. + +**1 — `goal complete` ignores an open Success Criteria box.** Page had `status: in_progress`, `# Success Criteria` with `- [ ] an open criterion`, `# Definition of Done` with `- [x] done item`. + +``` +$ vault-cli goal complete "ZZ Scratch Closure Gate" +✅ Goal completed: ZZ Scratch Closure Gate +EXIT=0 +$ grep -E '^status:' "24 Goals/ZZ Scratch Closure Gate.md" +status: completed +``` + +**2 — `goal complete` ignores an open task linked with brackets.** A task at `status: in_progress` with `goals:\n - '[[ZZ Scratch Link Goal]]'`; the goal had every SC and DoD box `[x]`. + +``` +$ vault-cli goal complete "ZZ Scratch Link Goal" +✅ Goal completed: ZZ Scratch Link Goal +LINK_EXIT=0 +``` + +The open-task guard did not fire. The same goal with the task linked as the bare name `ZZ Scratch Link Goal` refuses — that is the asymmetry `taskLinkedToGoal` produces. + +**3 — `topic complete` has no gate.** Page had `status: in_progress`, an open `# Success Criteria` box and an open `# Completion Gate` box. + +``` +$ vault-cli topic complete "ZZ Scratch Closure Gate" +✅ Topic completed: ZZ Scratch Closure Gate +TOPIC_EXIT=0 +``` + +**Code-level confirmation** (read at `a4fa4de`): + +- `pkg/ops/goal_complete.go:78-82` — the only pre-write guard is `checkOpenTasks`. +- `pkg/ops/goal_complete.go:185-192` — `taskLinkedToGoal` compares `g == goalName` over the raw `goals:` entries. +- `pkg/ops/topic_complete.go:36-66` — `Execute` finds, sets `status`, writes. No gate, no `--force`. + +## Expected vs Actual + +**Expected** — per the vault's closure rule (`50 Knowledge Base/Goal Closure Checklist.md` § Forcing function: *"every box must be `[x]` — no 'trust me', no 'deferred'"*, and `claude-supervisor/commands/steps/goal-closure.md` § What to do), a close verb refuses while any closure box is open or any member is non-terminal, and names what is open. A goal and a task close on `# Success Criteria` + `# Definition of Done`; a topic closes on `# Success Criteria` + `# Completion Gate`. + +**Actual** — `goal complete` reads neither section and its task guard misses bracketed links; `topic complete` reads nothing. Both exit 0 and write `status: completed`. + +## Why this is a bug + +`claude-supervisor/commands/steps/goal-closure.md:117-127` records the measurement this spec repeats and draws the conclusion explicitly: *"`vault-cli goal complete` re-checks **only** its open-task gate and reads no success criterion at all … a close it accepts is no evidence that any criterion was checked."* The supervisor therefore treats its own read as the authority and the verb as unable to disagree. That is a documented, accepted workaround for a missing gate, not the intended contract — and it holds only while every caller goes through the supervisor. A human running `vault-cli goal complete`, or any other tool, gets a close with no check. + +The link-matching half is a plain defect: the vault writes `goals:` as wikilinks (`'[[Finished Work Closes Itself]]'`), and the comparison never strips the brackets. + +## Assumptions + +- The closure rule is already written down and does not need re-deciding: section sets, verdict names, the `2026-06-26` grandfathering cutoff, the strict Completion Gate and the fence-stripping rule all come from `claude-supervisor/scripts/goal-closure-read.py` and `claude-supervisor/commands/steps/goal-closure.md`. The Go package ports them; it does not re-derive them. +- `DOD_REQUIRED_AS_OF = "2026-06-26"` lives in **three** places: `claude-supervisor/scripts/goal-closure-read.py:73`, this repo's `agents/goal-auditor.md:118`, and `agents/task-auditor.md:328`. (The vault's own `.claude/agents/goal-auditor.md` is a different, thinner auditor and carries no copy — do not chase it.) The cutoff is not moving in this change, so none of those three is edited; the Go port adds a fourth copy, and all four move together only if the cutoff ever moves. vault-cli cannot import from any of them. +- Topic member goals are read from the topic page's `## Goals` list. The supervisor's step declares that list as the tracked set (`claude-supervisor/commands/steps/goal-closure.md` § Which pages this covers). +- The `## Goals` list is **level-relative**, exactly as `agents/topic-manager-agent.md:67` states: `## Goals` runs past `###` sub-headings and ends at the next `#` or `##`; `# Goals` ends at the next `#`. Both spellings occur in the vault — four topic pages use the H1 form — and bounding at any heading, or at `##` only, under-reads members and lets an incomplete topic close. +- The in-repo closure-box table by kind already exists at `agents/goal-manager-agent.md`; this spec's section sets must agree with it. +- Terminal means `status: completed` or `status: aborted`, matching `TERMINAL_STATUSES` in the Python reader. +- `--output json` is already the CLI's structured-output channel; a refusal must populate it rather than only printing. + +## Goal + +`vault-cli goal complete` and `vault-cli topic complete` refuse to close a page whose own closure evidence is incomplete, and say exactly what is open — through one shared Go implementation in `pkg/ops`, so the two verbs cannot drift. A page whose evidence is complete closes exactly as it does today, and a page that is already terminal is a silent no-op rather than an error. + +## Non-goals + +- `objective complete`, `theme complete` and `vision complete`. `pkg/ops/objective_complete.go` carries the same ungated close and `objective complete` is a shipped verb, so the gap is real there too — it is out of scope here and needs its own spec, because the section sets for those tiers are not defined anywhere yet. +- `--force` on `topic complete`, and any change to `goal complete`'s existing `--force` semantics. +- Retrofitting historical pages: no page is rewritten, only future close calls are gated. +- Verifying that a ticked box is truthful. The gate reads markers, not evidence. +- Editing any `claude-supervisor` prompt or the vault's closure guide. + +## Acceptance Criteria + +All CLI-level criteria below run at **build time** against the binary built from the branch (`go test ./integration` builds and drives it through `createTempVaultWithGoals` for goal cases and `createTempVaultWithTopicPages` for topic cases, both in `integration/cli_test.go`). The installed-binary replay lives in § Verification § Operator-executable. + +- [ ] **Goal, open criterion refused.** An integration case drives `goal complete` on a temp-vault goal with one open `# Success Criteria` box and asserts: exit code non-zero, stdout carries that box's text, and the page still reads `status: in_progress`. Evidence: `go test ./integration -run TestIntegration -v` lists the case name and exits 0. +- [ ] **Goal, complete closes; both link forms guarded.** Three integration cases: (a) every SC and DoD box `[x]` and every linked task terminal → exit 0 and `status: completed`; (b) one open task linked as `[[]]` → non-zero exit naming that task; (c) the same task linked as the bare name → non-zero exit naming that task. Evidence: three case names in the `-v` listing. +- [ ] **Grandfathering is narrow.** Three integration cases: (a) no `# Definition of Done` section and `created` before `2026-06-26` → closes; (b) `# Definition of Done` heading present but holding no box → non-zero exit naming that section; (c) no DoD and `created` on or after the cutoff → non-zero exit. Evidence: three case names. +- [ ] **Topic gate.** Five integration cases: (a) one open `# Completion Gate` box → non-zero exit naming it; (b) one member goal not `completed`/`aborted` → non-zero exit naming that goal; (c) a member goal listed under a `###` sub-heading inside `## Goals`, non-terminal → still refused, so the bound is at the next `#`/`##` and not at any heading; (d) a topic whose member list is written as `# Goals` with a `##` sub-heading and a non-terminal member → still refused, so the bound is level-relative and not fixed at `##`; (e) SC and Completion Gate all `[x]` and every member goal terminal → exit 0 and `status: completed`. Evidence: five case names plus the written status. +- [ ] **Refusals enumerate, and JSON agrees.** An integration case on a page with two open items asserts the **plain** invocation's stdout carries one line per open item (two item lines), and that the same invocation with `--output json` yields `.open_items` whose length is 2. Evidence: `... --output json | jq '.open_items | length'` prints `2`, and the plain invocation's stdout line count equals it. +- [ ] **Terminal is a no-op.** An integration case runs each verb against an already-`completed` page and an `aborted` page: exit 0, and the file's `sha256` is identical before and after. Evidence: four cases, each asserting the digest. +- [ ] **One implementation, and the port is faithful.** Both verbs call one shared check in `pkg/ops`, named `checkClosureGate` — evidence: `grep -n 'checkClosureGate' pkg/ops/goal_complete.go pkg/ops/topic_complete.go` returns exactly one line per file, and `grep -cE '\[[ xX/-]\]' pkg/ops/goal_complete.go pkg/ops/topic_complete.go` returns `0` for each. A table test names at least these cases and passes: SC box open (OPEN), DoD section present-but-empty (UNMEASURABLE), DoD absent with `created` before the cutoff (CLOSE, grandfathered), DoD heading in a non-`#` spelling with no boxes (UNMEASURABLE, not grandfathered), a `*`-bulleted open box (OPEN), an unrecognised `-` or `?` marker (OPEN), a box inside a fenced block with no real box (UNMEASURABLE), an unterminated fence (UNMEASURABLE), a BOM-prefixed CRLF page (frontmatter still read), Completion Gate box open (OPEN), Completion Gate mixing a checkbox with an ordered-list item (UNMEASURABLE), member goal not terminal (OPEN), already-`completed` page (TERMINAL → exit 0 no-op). **Each case asserts its own expected verdict** — a case that merely runs is not evidence. Evidence: `go test ./pkg/ops -run TestSuite -ginkgo.focus=Closure -ginkgo.v` lists every one of those case names and exits 0. + +## Verification + +### Container-executable (runs inside the YOLO container at prompt time) + +- `make precommit` — exits 0 +- `make test` — exits 0 +- `go test ./pkg/ops -run TestSuite -ginkgo.focus=Closure -ginkgo.v` — lists the table cases required by the last AC +- `go test ./integration -run TestIntegration -v` — lists the CLI cases required by AC1-6 +- `go vet ./pkg/ops/... ./integration/...` — exits 0 + +### Operator-executable (runs on the host after the release is installed) + +- `vault-cli --version` shows the released tag +- Replay the three probes from § Reproduction against that binary. The discriminating signal is the **verdict**, not the exit code alone: probes 1 and 3 must now print a refusal naming the open item and leave `status: in_progress`; probe 2 must refuse naming the bracketed-linked task. +- Re-run the positive half: a fully-ticked scratch goal and topic close with exit 0 and `status: completed`, and a second invocation on the now-`completed` page exits 0 with an unchanged file digest. + +## Desired Behavior + +1. `goal complete` and `topic complete` consult one shared closing check in `pkg/ops` before any write. No second copy of the rule exists in either verb. +2. Section sets are fixed by kind, never guessed from the page: goal and task → `# Success Criteria` + `# Definition of Done`; topic → `# Success Criteria` + `# Completion Gate`. +3. A section that is absent, or present with zero boxes, is unmeasurable and refuses the close. An empty section is never treated as vacuously complete. +4. A box counts as done only for the marker `x` or `X`. Every other marker — including ` `/`/`, and an unrecognised one such as `-` or `?` — counts as open. Bullets `-`, `*` and `+` all count. +5. Fenced code blocks are stripped over the whole document before sections are located; an unterminated fence refuses the close. A checkbox inside a fence is an example, never a box. +6. Grandfathering applies to **goals only**, to **absence only**: an absent `# Definition of Done` is accepted when the frontmatter parsed and `created` is absent or lexicographically earlier than `2026-06-26`. It is skipped entirely if any DoD-shaped heading exists anywhere on the page, in any spelling. An empty DoD heading stays unmeasurable. +7. The `# Completion Gate` is read strictly: a section carrying any list item that is not a checkbox is out of compliance and refuses the close. +8. Line endings are normalised and a BOM stripped before frontmatter is read, so the `status:` line cannot be lost. (This is an addition beyond the ported reader, which assumes `\A---\n` — it guards the same failure the reader documents for CRLF pages.) +9. A page already at `completed` or `aborted` exits 0 and is not written. This is a deliberate deviation from **both** baselines: the Python reader returns `TERMINAL → exit 1`, and vault-cli today returns an `already completed` error. Re-closing a finished page is a no-op, not an error, so a closure loop that ticks repeatedly stays silent. +10. A refusal exits 1, prints one line per open item, and populates `--output json` with the same items as an array under `open_items`. +11. Linked-task matching normalises both forms, so `[[Some Goal]]` and `Some Goal` in a task's `goals:` both count. The existing open-status set (`next`, `todo`, `in_progress`) is unchanged. +12. A topic refuses while any goal listed in its `## Goals` section — bounded at the next `#` or `##` heading — is not `completed` or `aborted`, naming that goal. **The bound is level-relative and covers both spellings**: `## Goals` runs past `###` sub-headings and ends at the next `#` or `##`; `# Goals` ends at the next `#`. Four live topic pages write the H1 form, so a reader that looks only for `## Goals` finds zero members there and closes them unexamined. + +## Constraints + +- **Do not change `task complete`'s behaviour.** Its whole-page box gate is already correct and is the model, not a target. +- **Do not shell out to, import, or depend on `claude-supervisor`.** The two plugins are installed independently and vault-cli must work when the other is absent. +- **The check is read-only.** It must never write, create or delete anything. +- **`pkg/ops` is a library layer** — it returns structured results and never writes to stdout; the CLI layer owns all output formatting (`CLAUDE.md` § Key Design Decisions). +- **The refusal's JSON field is `open_items`** (a `[]string` on `MutationResult`). The ACs and the jq probe both name it, so the prompt must not invent a different name. +- **Invert, do not delete, the two existing terminal tests.** `pkg/ops/goal_complete_test.go:88-96` and `pkg/ops/topic_complete_test.go:121-138` both assert an `already completed` error. DB9 inverts that behaviour, so these two contexts must be rewritten to assert exit-0/no-write — never removed. +- **Error wrapping** goes through `github.com/bborbe/errors`, never `fmt.Errorf`. +- **Do not hand-bump version manifests or tag.** `.maintainer.yaml` carries `autoRelease: true`; the releaser owns the tag post-merge. `.dark-factory.yaml` carries `autoRelease: false` for the container run. +- **Add a `## Unreleased` CHANGELOG bullet.** +- Existing `--force` semantics on `goal complete` are unchanged and stay narrow: `--force` bypasses **only** the open-task gate, never the closure gate — a forced close still cannot close a page with an open criterion. `topic complete` gains no `--force` in this change. + +## Failure Modes + +| Trigger | Expected behavior | Recovery | +|---|---|---| +| Page frontmatter does not parse | Refuse; never grandfather it (an unreadable page is not a page with no `created`) | Repair the frontmatter and re-run | +| Unterminated code fence | Refuse as unmeasurable | Close the fence | +| DoD heading written as `## Definition of Done`, a setext heading, or `- Definition of Done` | Treated as a present section for the grandfathering guard, so the exemption is not granted | Normalise the heading to `# Definition of Done` | +| `created` in a non-ISO shape (`15.01.2026`, `2026`) | Not grandfathered — refused rather than compared | Write `created` as a zero-padded ISO date | +| A topic with an empty `## Goals` list | Closes on its own SC + Gate boxes alone | None; a topic with no members is legitimate | +| A `## Goals` entry grouped under a `###` sub-heading | Still read — the list ends at the next `#` or `##`, not at any heading | None | +| A topic whose member list is written as `# Goals` with a `##` sub-heading | Still read to the next `#` — the bound is level-relative, not fixed at `##` | None | +| Concurrent vault write during the check | Check is read-only and takes its snapshot from the page it already loaded | Re-run the verb | +| Gate passes, then `WriteGoal`/`WriteTopic` fails | Non-zero exit and the page stays at `status: in_progress` — the write is the only mutation | Re-run the verb; the check is read-only so the retry is idempotent | +| Two goals share a name across folders | Existing name resolution applies unchanged | Not a new surface | + +## Suggested Decomposition + +**One prompt, deliberately.** The change is one behavioural rule — a page closes only on its own recorded evidence — expressed in one shared `pkg/ops` check and two call sites. Splitting it is unsafe for a pipeline reason rather than a design one: dark-factory assigns prompt numbers by sorting *unprefixed* filenames alphabetically and gates each prompt on every lower-numbered prompt of the same spec, so a four-row split cannot be made to sort in dependency order. Observed on spec 067 (2026-11-16): a three-row decomposition normalised to docs → fixtures → guard, the docs row failed on a verification that needed the guard's output, and the other two blocked behind it. A row that wires a call site before the shared check exists is that same deadlock. + +| # | Prompt focus | Covers DBs | Covers ACs | Depends on | +|---|---|---|---|---| +| 1 | The shared closure check in `pkg/ops` (sections by kind, verdicts, grandfathering, strict gate, fence stripping, normalisation) plus its table test; wire it into `goal_complete.go` and `topic_complete.go`; fix link normalisation; add the topic member-goal check; wire the refusal output, the `open_items` field and `--output json`; the integration cases; the `## Unreleased` bullet | 1-12 | 1-7 | — | + +*Scope note: DBs × ACs = 12 × 7 = 84, over the 50 split-threshold. Not split — the ordering constraint above makes a single prompt the only shape this pipeline executes correctly, and the bounded surface is one new file plus two call sites and their tests.* + +## Do-Nothing Option + +Doing nothing is not neutral, because the gap is already being papered over in one place. The supervisor's `goal-closure-read.py` computes the correct verdict and its closure step treats that read as the authority — so **supervisor-driven** closes are already correct, and staying as-is costs nothing there. + +Every other caller gets the silent close this spec reproduces: a human running `vault-cli goal complete`, any script, any future tool, and the topic tier even under the supervisor (which has no topic-close reader). The two tiers then disagree with the third — `task complete` refuses on an open box while `goal complete` and `topic complete` do not — and the vault's own closure guide has to keep carrying a caveat that the CLI cannot be trusted to enforce its rule. + +Doing nothing also leaves the link-matching defect in place, which silently disables the one guard that does exist. Cost of the fix is one shared check plus two call sites; cost of not fixing is that the forcing function holds at one tier out of three.