beads/cmd/bd/memory_pure_test.go
Stephanie Jarmak 559b5de1e2
fix(memory): preserve presence for empty values (#5964)
* fix(memory): preserve presence for empty values (#5963)

Recall and Forget now distinguish an existing empty memory row from an absent key across direct, embedded, and UOW storage paths.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of sjarmak

* fix(memory): make bd recall report presence from row existence

printRecallResult (and the recallCmd caller) derived "found" from
value != "", so a memory stored as the empty string still printed
"No memory with key" and exited 1 even though the role's
RecallResult.Found was true and bd forget would delete the row.
Thread result.Found through instead: an empty-valued memory now
recalls cleanly (exit 0, empty value; JSON reports found: true), and
only an absent key is a miss.

Addresses maintainer review on #5964 (fixes #5963).

* test(httpapi): pin GET /v0/beads/memories/{key} as 200 for an empty value

TestGetMemoryAnswersAMissWithA404 pinned a RecallResult{Value: ""}
case (Found defaulting to its zero value, false) as a 404, a shape no
backend can produce since Found now comes from row existence rather
than value truthiness. Move that case into its own
TestGetMemoryAnswersAnEmptyValueWith200, which recalls Found: true
and asserts a 200 with an empty value. Also updates the handler's
doc comment, which still described the retired 404-on-empty
behavior.

Addresses maintainer review on #5964 (fixes #5963).

* docs(httpapi): fix openapi spec to say memory presence is row existence

The published spec still said an empty-valued memory is a 404 on
GET /v0/beads/memories/{key} and DELETE /v0/beads/memories/{key},
contradicting the role's RecallResult.Found (row existence). Rewrite
the operation descriptions, both 404 response bodies, Memory.value
and RememberedMemory.replaced to say presence is row existence
everywhere: an empty-string memory is a 200 (or is removed by
forget) with an empty value, matching what GET /v0/beads/memories
already enumerated. Regenerate types.gen.go via `make api-gen` so
the generated doc comments match.

Addresses maintainer review on #5964 (fixes #5963).

* docs(changelog): note the empty-valued memory presence fix

Add an Unreleased/Fixed entry for #5964 (fixes #5963): bd recall,
bd forget and GET /v0/beads/memories/{key} now treat an empty-valued
memory as present everywhere, instead of only on GET
/v0/beads/memories.

* fix(memory): make bd remember <bare-key> recall an empty-valued memory

rememberBareKeyPath decided presence from existing != "", so a bare slug
naming a memory stored as the empty string was refused as "no memory
named" instead of recalled. It now takes the role's Found, matching
printRecallResult, bd forget and the HTTP door.

* test(memory): pin empty-value presence through the real commands

TestPrintRecallResult and TestRememberBareKeyPath call the helpers directly,
so a RunE that went back to deciding presence from value != "" would leave
them green. TestEmbeddedMemory/empty_valued_memory_is_present empties a
memory row beneath bd and runs bd recall, bd remember <bare-key> and
bd forget against it, checking first that bd no longer sees the placeholder.

Two comments in problem.go and one in memories_test.go still said an
empty-valued memory is a 404. The CHANGELOG line now says a key with no row
is a miss, since a forgotten key was once stored.

* build(bazel): add the memoryops dep to the bd_test go_test (make bazel-sync)

memory_embedded_test.go now imports internal/storage/memoryops directly
(storagememoryops.StorageKey, to overwrite a memory row out of band), so
gazelle emits //internal/storage/memoryops on bd_test. cmd/bd/BUILD.bazel
landed on main after this PR branched, so the PR could not carry the dep;
without it, bazel.yml's "BUILD files in sync" step fails in the required
bazel-test lane. Generated by `make bazel-sync`.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(memory): maintainer fixup — adoption review nits

Maintainer fixup for the adopt-pr iteration-1 review of #5964. Both review
lanes approved and the quality scorecard approved at 981; these are its four
non-gating nits, each confined to lines this PR already adds.

- internal/httpapi: TestForgetMemoryOfAnEmptyValuedKeyIs200 pins the DELETE
  door's empty-value 200 the way TestGetMemoryAnswersAnEmptyValueWith200
  pins the read. Guarding the handler's 404 on Value == "" reddens exactly
  this test and nothing else.
- CHANGELOG: the bullet names DELETE /v0/beads/memories/{key} beside GET,
  whose answer changed the same way (404 with the row left standing -> 200
  with the row removed).
- uow: the two new GetAllConfig presence probes in Recall and Forget say why
  they read the whole table, by pointing at Remember's rationale.
- conformance: RunMemoriesEmptyRowIsPresentUntilForgotten runs its
  no-history-on-retry leg last and SKIPs it with a reason when a fixture has
  no CountHistory, as the MemoriesFixture doc promises, instead of passing
  quietly. All three in-tree fixtures wire the hook, so every in-tree run
  is unchanged (19/19 on dolt, embeddeddolt and uow, 0 SKIP).

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(httpclient): report an empty-valued memory as present (base-refresh repair)

Maintainer repair from refreshing #5964 onto main b630f96f5b. Main's #7247
added the HTTP client store (internal/httpclient) after this PR branched,
and its memory role and served conformance leg still treated a memory
stored as the empty string as absent:

- Recall set Found from Value != "".
- The RecallMemory doc said an empty-valued row was a 404.
- TestServedMemoriesRecallConflatesStoredEmptyWithAbsent called
  conformance.RunMemoriesRecallConflatesStoredEmptyWithAbsent, which this
  PR deletes.

The rebase applied cleanly, but the merged tree did not compile.

- internal/httpclient/memories.go: Recall reports Found true on any 200.
  With this PR the wire returns a 404 only for a key with no row; an
  empty-valued row comes back as a 200 with an empty value. Setting Found
  from Value would hide that row again on the HTTP backend. Forget already
  reported Found true on a 200.
- internal/httpclient/wire/writes.go: the RecallMemory doc now says the
  same.
- internal/httpclient/served_memories_deps_test.go: the hm10 served case
  now runs RunMemoriesEmptyRowIsPresentUntilForgotten, the contract case
  this PR adds in place of the one it deletes.

With BEADS_TEST_EMBEDDED_DOLT=1 the served memory tests pass with 0 SKIP.
Reverting the Recall line makes hm10 fail with
`Recall("hm10-stored-empty") = value "" found false, want value "" found
true`.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: sjarmak <t@t.co>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 19:28:54 +00:00

197 lines
6.2 KiB
Go

// Pure-Go tests for memory command helpers. No cgo / Dolt dependency, so this
// file carries no build tag and compiles under CGO_ENABLED=0 with gms_pure_go.
package main
import (
"encoding/json"
"strings"
"testing"
)
// TestMatchesKnownCommand guards the `bd remember <subcommand>` misfire fix
// (GH#4401): a bare word that names a real top-level command must be flagged so
// it is not silently stored as memory content, while genuine multi-word
// insights (and arbitrary single words) must pass through untouched.
func TestMatchesKnownCommand(t *testing.T) {
cases := []struct {
name string
insight string
wantName string
wantHit bool
}{
{"sibling command recall", "recall", "recall", true},
{"sibling command forget", "forget", "forget", true},
{"sibling command memories", "memories", "memories", true},
{"remember itself", "remember", "remember", true},
{"case insensitive", "ReCall", "recall", true},
{"multi-word insight", "always run tests with the -race flag", "", false},
{"leading command word in a phrase", "recall the auth design", "", false},
{"non-command single word", "zorblax", "", false},
{"empty", "", "", false},
{"whitespace only", " ", "", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
gotName, gotHit := matchesKnownCommand(rememberCmd, tc.insight)
if gotHit != tc.wantHit {
t.Fatalf("matchesKnownCommand(%q) hit = %v, want %v", tc.insight, gotHit, tc.wantHit)
}
if gotHit && gotName != tc.wantName {
t.Errorf("matchesKnownCommand(%q) name = %q, want %q", tc.insight, gotName, tc.wantName)
}
})
}
}
// TestPrintRecallResult guards the bd-5963 fix: presence must come from
// `RecallResult.Found` (row existence), never from `value != ""`. Before the
// fix, `bd recall` on a memory stored as the empty string printed "No memory
// with key" and exited 1 even though the row was there and `bd forget` would
// delete it — the CLI disagreed with the role and with the HTTP door about
// what "found" means for that row.
func TestPrintRecallResult(t *testing.T) {
t.Run("found with empty value prints the empty value and exits clean", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = false
defer func() { jsonOutput = savedJSONOutput }()
var err error
out := captureStdout(t, func() error {
err = printRecallResult("empty-key", "", true)
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out != "\n" {
t.Errorf("stdout = %q, want a single newline (the empty value)", out)
}
})
t.Run("found with empty value in JSON reports found true", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = true
defer func() { jsonOutput = savedJSONOutput }()
var err error
out := captureStdout(t, func() error {
err = printRecallResult("empty-key", "", true)
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var body map[string]interface{}
if uerr := json.Unmarshal([]byte(strings.TrimSpace(out)), &body); uerr != nil {
t.Fatalf("unmarshal %q: %v", out, uerr)
}
if body["found"] != true {
t.Errorf("found = %v, want true", body["found"])
}
if body["value"] != "" {
t.Errorf("value = %v, want \"\"", body["value"])
}
if body["key"] != "empty-key" {
t.Errorf("key = %v, want %q", body["key"], "empty-key")
}
})
t.Run("found with non-empty value is unchanged", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = false
defer func() { jsonOutput = savedJSONOutput }()
var err error
out := captureStdout(t, func() error {
err = printRecallResult("k", "hello", true)
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out != "hello\n" {
t.Errorf("stdout = %q, want %q", out, "hello\n")
}
})
t.Run("not found prints the miss and exits 1", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = false
defer func() { jsonOutput = savedJSONOutput }()
var err error
stderr := captureStderr(t, func() {
err = printRecallResult("gone", "", false)
})
if !strings.Contains(stderr, `No memory with key "gone"`) {
t.Errorf("stderr = %q, want it to name the missing key", stderr)
}
ee, ok := err.(*exitError)
if !ok || ee.Code != 1 {
t.Errorf("err = %v, want *exitError{Code: 1}", err)
}
})
t.Run("not found in JSON reports found false and exits 1", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = true
defer func() { jsonOutput = savedJSONOutput }()
var err error
out := captureStdout(t, func() error {
err = printRecallResult("gone", "", false)
return nil
})
var body map[string]interface{}
if uerr := json.Unmarshal([]byte(strings.TrimSpace(out)), &body); uerr != nil {
t.Fatalf("unmarshal %q: %v", out, uerr)
}
if body["found"] != false {
t.Errorf("found = %v, want false", body["found"])
}
ee, ok := err.(*exitError)
if !ok || ee.Code != 1 {
t.Errorf("err = %v, want *exitError{Code: 1}", err)
}
})
}
// TestRememberBareKeyPath guards the same presence rule on the
// `bd remember <bare-slug>` read path: a bare slug naming a memory stored as
// the empty string recalls it, and only a slug naming nothing is refused.
func TestRememberBareKeyPath(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = true
defer func() { jsonOutput = savedJSONOutput }()
t.Run("found with empty value recalls it", func(t *testing.T) {
var err error
out := captureStdout(t, func() error {
err = rememberBareKeyPath("empty-key", "empty-key", "", true)
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var body map[string]interface{}
if uerr := json.Unmarshal([]byte(strings.TrimSpace(out)), &body); uerr != nil {
t.Fatalf("unmarshal %q: %v", out, uerr)
}
if body["action"] != "recalled" || body["found"] != true || body["value"] != "" {
t.Errorf("body = %v, want action recalled, found true, empty value", body)
}
})
t.Run("not found is refused", func(t *testing.T) {
var err error
captureStdout(t, func() error {
err = rememberBareKeyPath("gone", "gone", "", false)
return nil
})
ee, ok := err.(*exitError)
if !ok || ee.Code != 1 {
t.Errorf("err = %v, want *exitError{Code: 1}", err)
}
})
}