beads/memoryops/memories.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

187 lines
8.6 KiB
Go

package memoryops
import "context"
// RememberRequest stores one memory.
type RememberRequest struct {
// Key names the memory to store under. EMPTY MEANS DERIVE IT from Content,
// using the one canonical derivation (internal/memoryapi.DeriveKey — the
// function that has minted every auto-generated memory key since the
// command shipped). A request with no key is the NORMAL case, which is why
// the role derives rather than making the caller learn the derivation.
//
// A non-empty Key is used VERBATIM: no trimming, no slugging, no charset
// restriction. `bd remember --key` has always accepted any string, and a
// stored key has to stay recallable under the exact bytes the caller used.
Key string
// Content is the memory itself.
//
// Empty after trimming is ErrValidation. So is content from which no key
// can be derived when Key is empty — "!!!" derives to "" — because the
// alternative is a row under a key nothing can name.
//
// Otherwise it is stored VERBATIM: newlines, surrounding space and unicode
// all survive. Truncating it to one line is what a front door does when it
// prints; it is not what this plane does when it stores.
Content string
}
// RememberResult reports what landed.
type RememberResult struct {
// Key is the key the memory now lives under: the request's, or the derived
// one. A caller that supplied no key learns here what to recall.
Key string
// Value echoes the stored content, verbatim.
Value string
// Replaced reports whether a previous value existed under Key, OBSERVED IN
// THE SAME TRANSACTION AS THE WRITE. It is what the CLI's "Remembered"
// versus "Updated" verb is made of, and unlike the two-step read it
// replaces it cannot be stale: no concurrent write can land between the
// observation and the act it describes.
//
// A previous value that was the EMPTY STRING reports Replaced true. The ROW
// existed, regardless of what it held.
Replaced bool
}
// RecallRequest names one memory to read. An empty Key, or one that is empty
// after trimming, is ErrValidation: there is no row a caller could mean by it,
// and answering Found false would report "no such memory" for a question that
// was never asked.
type RecallRequest struct{ Key string }
// RecallResult is one memory's stored content.
type RecallResult struct {
// Key echoes the request.
Key string
// Value is the stored content, or "" — and Found says how to read the "".
Value string
// Found reports whether the row exists, independently of Value. A memory
// stored as the empty string therefore reports Found true; an absent memory
// reports Found false with the same empty Value.
Found bool
}
// ForgetRequest names one memory to remove. An empty Key is ErrValidation, for
// the reason RecallRequest's is.
type ForgetRequest struct{ Key string }
// ForgetResult reports the removal.
type ForgetResult struct {
// Key echoes the request.
Key string
// Value is the content the removed memory held — what `bd forget` prints —
// read in the SAME TRANSACTION as the delete, so it is what was actually
// removed rather than what a previous read happened to see.
Value string
// Found false means no row was stored under Key and NOTHING WAS DELETED. A
// row holding the empty string is found and deleted.
//
// It is a result, not an error. The front doors own the not-found
// presentation — the CLI has an exit-code contract for it — and a role that
// returned an error here would force every one of them to classify a
// refusal to learn a fact.
Found bool
}
// ListRequest asks for the memory plane, optionally narrowed.
type ListRequest struct {
// Search filters the answer: a memory matches when the lowercase of its key
// or the lowercase of its value contains the lowercase of Search. "" means
// everything.
//
// THE FOLDING IS THIS ROLE'S, not the caller's. A caller passes what the
// user typed; it does not pre-lower the term. That is the difference
// between a role that owns the matching semantics and one that documents
// them and hopes.
Search string
}
// ListResult is the memory plane, narrowed by the request's Search.
type ListResult struct {
// Memories maps USER key (prefix stripped) to stored value, for every row
// of the memory plane that matched — and ONLY the memory plane. Settings
// rows, generic `bd kv` rows and every other row of the config table this
// plane shares are never here, whatever they contain, INCLUDING a memory
// whose key shadows a settings name: "kv.memory.issue_prefix" is a memory
// called "issue_prefix" and the workspace's real prefix is not a memory.
//
// Empty map, never nil, so a caller can range over the answer without a
// guard. No order and no page: callers that print sort the keys, as both
// front doors do today.
Memories map[string]string
}
// Memories describes the workspace's persistent memory plane — see the package
// doc for what that plane is and why it is not the settings plane.
//
// IT IS ONE PLANE, WHICH IS WHY IT IS ONE ROLE WITH FOUR METHODS. Store, read,
// remove and enumerate over a single keyed namespace are four shapes of one
// question, the same argument that made issueops.WorkspaceConfig one role with
// four. The promises are statements about each other — what Remember stores is
// what Recall answers and what Forget reports it removed — so splitting them
// would put one role's promise inside another role's result.
//
// The read/write entitlement test the role rule applies (can one caller be
// entitled to the read and not the write?) comes back NO here: bd's readonly
// mode is a front-door guard applied uniformly across every role, and no
// shipped path is forbidden to write memories the way a provisioned identity is
// forbidden to write a workspace identity. If a genuinely read-only memory
// consumer appears — a credential that may read prime context but not write it
// — that is the day to mint a MemoryReader. Being born whole is allowed;
// appending later is not, and splitting later is cheap because the four methods
// already have separate request types.
//
// PROBE AND ACT SHARE ONE TRANSACTION on every implementation. Remember's
// Replaced and Forget's Value are observations of the row the same transaction
// then writes or deletes, not the results of an earlier read. The shipped
// commands did it in two calls and papered over the gap by ignoring the first
// one's error; this role does not, which also means a database that cannot be
// read now FAILS the write rather than mis-reporting it.
//
// Deterministic request-validation failures match ErrValidation; result values
// are unspecified when error is non-nil. Implementations never mutate
// caller-owned request values.
type Memories interface {
// Remember stores one memory, deriving its key from the content when the
// request supplies none, and reports whether it replaced a previous value.
//
// THE REFUSALS, in the order they are applied:
//
// - Content empty after trimming is ErrValidation. There is nothing to
// remember;
// - Content from which no key can be derived, when Key is empty, is
// ErrValidation. The caller's recourse is an explicit key, which the
// message says.
//
// A Remember of the value already stored still performs the write. Nothing
// compares first: this plane converges on merge, so a write that decided it
// was a no-op would be a write that declined to state a fact the merge
// resolver reads.
Remember(ctx context.Context, req RememberRequest) (RememberResult, error)
// Recall returns one memory's content, or Found false.
//
// It is a READ: nothing here records a history entry, fires a completion
// hook or changes a row. A key nothing stored is Found false with a nil
// error, never ErrNotFound — see errors.go for why that is a decision and
// not an omission.
Recall(ctx context.Context, req RecallRequest) (RecallResult, error)
// Forget removes one memory and reports what it held.
//
// Removing a key nothing stored is a SUCCESS with Found false, and it
// deletes nothing — including nothing from the settings plane or the
// generic kv namespace that share this table. Forgetting the same key twice
// is the second call a retrying caller actually makes, and it answers the
// same way.
Forget(ctx context.Context, req ForgetRequest) (ForgetResult, error)
// List returns the memory plane, narrowed by the request's Search.
//
// A read, on the same terms as Recall, and one that SUBSUMES the matching:
// the caller hands over the search term the user typed and this role owns
// what matching means. A miss answers an empty map, never nil and never an
// error.
List(ctx context.Context, req ListRequest) (ListResult, error)
}