Files
ely-eye/ely-eye-mcp/internal/apiclient/client.go
T
ZacharyZhang-NY dc9cfb5a30 Give memories a working tier, a long-term tier, and a record of what disagrees
A memory used to have one state: present. A session could not be reloaded
without searching, nothing separated what a person said today from what the
store ingested a year ago, and two statements that disagree about a number
were both handed to the reader as if the store believed both.

Schema v10. Atoms gain session_id, importance, recall_count, last_recalled_at
and archived_at; two tables arrive beside them — consolidations (one watermark
per holder+scenario lane) and conflicts (a pair, the term they disagree on,
both values, and whether anyone has settled it). v_atoms_current now also
hides archived rows, and apply() drops the view before rebuilding it because
CREATE VIEW IF NOT EXISTS would keep the old body and ignore the archive.

Working memory is a read, not a store: `working <holder> <session>` returns
what that session recorded, in order, with no search involved. Consolidation
rolls a lane's new memories into one standing summary and moves the watermark
to the newest memory actually rolled up — not to the clock of the pass, which
made a second pass count the same memories twice. The archive rule is stated
in the command that runs it (recorded before N days, never returned by a
search, importance at or under a floor) rather than hidden in a decay formula
nobody measured; --dry-run names the victims first.

A conflict is recorded when a new memory repeats a label with a different
number in the same holder's same scenario. Retrieval drops the older side
while the conflict is open and both sides answer again once it is settled:
settling is not superseding, and a word-only disagreement is left alone
because a reworded sentence would fire on every paraphrase. Numbers are keyed
to both the memory's subject and the nearest preceding label, measured: the
two thermostat sentences share only their subject, so a nearest-word-only rule
found nothing.

Search now counts the memories it handed back, which is the only use estimate
the store has, and the archive rule reads it. The dense index applies the same
currency rules as the view, so an archived memory cannot stay findable through
one leg while the other hides it.

Two reads over HTTP (working, conflicts) and two tools over MCP
(working_set, memory_conflicts); curation stays with the operator because an
agent should not decide what its own past is worth. remember and supersede
carry a session id; importance does not cross MCP, because recall_count is
observed and importance is stated.

Gates: 366 passed; ruff clean; mypy 24 errors in 9 files, the recorded 9cb46c1
baseline, net 0; pyright 0 on the touched files; go build/vet/test and gofmt
clean; mcp_write_smoke PASS.
2026-10-09 07:13:11 -04:00

193 lines
5.8 KiB
Go

// Package apiclient talks to a running Ely-Eye API server. The Python service
// owns every write rule, so the MCP server forwards mutations instead of
// duplicating them against SQLite.
package apiclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/ZacharyZhang-NY/ely-eye/ely-eye-mcp/internal/domain"
)
const maxErrorBody = 4096
type Client struct {
BaseURL string
Token string
HTTP *http.Client
}
func New(baseURL string) *Client {
if strings.TrimSpace(baseURL) == "" {
baseURL = "http://127.0.0.1:8765"
}
return &Client{
BaseURL: strings.TrimRight(baseURL, "/"),
Token: strings.TrimSpace(os.Getenv("ELY_EYE_AUTH_TOKEN")),
HTTP: &http.Client{Timeout: 30 * time.Second},
}
}
// authorize attaches the write token; the server refuses a write without it.
func (c *Client) authorize(request *http.Request) {
if c.Token != "" {
request.Header.Set("Authorization", "Bearer "+c.Token)
}
}
// Get fetches a JSON resource into out.
func (c *Client) Get(ctx context.Context, path string, out any) error {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+path, nil)
if err != nil {
return fmt.Errorf("cannot build the request for %s: %w", path, err)
}
c.authorize(request)
return c.do(request, path, out)
}
func (c *Client) do(request *http.Request, path string, out any) error {
response, err := c.HTTP.Do(request)
if err != nil {
return fmt.Errorf("the Ely-Eye API at %s is unreachable; start it with `ely-eye serve`: %w", c.BaseURL, err)
}
defer response.Body.Close()
data, err := io.ReadAll(io.LimitReader(response.Body, maxErrorBody))
if err != nil {
return fmt.Errorf("%s returned an unreadable body: %w", path, err)
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return errors.New(path + " was rejected: " + serverReason(response.StatusCode, data))
}
if out == nil {
return nil
}
if err := json.Unmarshal(data, out); err != nil {
return fmt.Errorf("%s returned JSON that does not decode: %w", path, err)
}
return nil
}
// Post sends body as JSON and decodes the response into out. A rejected request
// carries the server's own reason, which is the rule the caller broke.
func (c *Client) Post(ctx context.Context, path string, body any, out any) error {
payload, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("cannot encode the request for %s: %w", path, err)
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, bytes.NewReader(payload))
if err != nil {
return fmt.Errorf("cannot build the request for %s: %w", path, err)
}
request.Header.Set("Content-Type", "application/json")
c.authorize(request)
return c.do(request, path, out)
}
// serverReason prefers FastAPI's {"detail": "..."} so the caller sees the broken
// rule instead of an HTML error page.
func serverReason(status int, data []byte) string {
var envelope struct {
Detail string `json:"detail"`
}
if err := json.Unmarshal(data, &envelope); err == nil && strings.TrimSpace(envelope.Detail) != "" {
return envelope.Detail
}
trimmed := strings.TrimSpace(string(data))
if trimmed == "" {
return fmt.Sprintf("HTTP %d with no reason", status)
}
return trimmed
}
// WorkingSet asks for what one session recorded, in the order it recorded it,
// with no ranking involved. The session is required: without one, every memory
// in the store would be working memory.
func (c *Client) WorkingSet(ctx context.Context, holder, session string) ([]domain.Memory, error) {
if strings.TrimSpace(holder) == "" {
return nil, errors.New("holder is required")
}
if strings.TrimSpace(session) == "" {
return nil, errors.New("session is required")
}
path := "/api/memory/working?holder=" + url.QueryEscape(holder) + "&session=" + url.QueryEscape(session)
var atoms []domain.Memory
if err := c.Get(ctx, path, &atoms); err != nil {
return nil, err
}
return atoms, nil
}
// Conflicts lists the disagreements the store noticed and nobody has settled.
// An empty holder asks for every holder's, which is what an operator reviewing
// the whole store wants.
func (c *Client) Conflicts(ctx context.Context, holder string) ([]domain.ConflictRecord, error) {
path := "/api/memory/conflicts"
if strings.TrimSpace(holder) != "" {
path += "?holder=" + url.QueryEscape(holder)
}
var records []domain.ConflictRecord
if err := c.Get(ctx, path, &records); err != nil {
return nil, err
}
return records, nil
}
// SearchOptions is one ranked query. Empty optional fields are omitted, so the
// server's own defaults decide rather than a zero value invented here.
type SearchOptions struct {
Query string
Modality string
Holder string
Scenario string
Limit int
}
// SearchResult carries the server's own verdict: "no_match" is a claim about the
// corpus, an empty hit list is not.
type SearchResult struct {
Status string `json:"status"`
Hits []domain.AtomHit `json:"hits"`
NextCursor string `json:"next_cursor"`
}
// Search asks the running server to rank. The ranking lives in one place, so an
// MCP hit cannot disagree with an HTTP or CLI hit for the same query.
func (c *Client) Search(ctx context.Context, options SearchOptions) (*SearchResult, error) {
if strings.TrimSpace(options.Query) == "" {
return nil, errors.New("query is required")
}
body := map[string]any{"query": options.Query}
if options.Limit > 0 {
body["top_k"] = options.Limit
}
filters := map[string]string{}
for key, value := range map[string]string{
"modality": options.Modality,
"holder": options.Holder,
"scenario": options.Scenario,
} {
if value != "" {
filters[key] = value
}
}
if len(filters) > 0 {
body["filters"] = filters
}
var result SearchResult
if err := c.Post(ctx, "/api/search", body, &result); err != nil {
return nil, err
}
return &result, nil
}