memdistill: finished conversations proposed as memories to review
A model reads an agent's session once it has been quiet for 30 minutes and writes down what will hold beyond it: a stated preference, a rule from a correction, a project fact the code doesn't say. Each one waits in memory as a candidate (To review), with the session, folder and the user's words it came from; nothing reaches an agent until kept. - Off until switched on (distill.json); switched on, it looks back 7 days. - Main sessions only: no subagents, gateway-only or read-only sessions, none of its own (agent "memory"), and two user turns at least. - At most 10 sessions a run, the latest first; a session is read again only once it goes on. A model that fails stops the run and says why; the sessions not read are read next time. - The model is sent user and assistant text alone (no thinking, tool calls or results), cut to 24k characters (start and end), with the memories already known so they aren't proposed again. Its instructions name neither the app nor a vendor. - A distilled memory the user deleted isn't proposed again (2e0058330). - An unreadable distill.json is never written over, and nothing runs. Not wired to the gateway or the GUI yet (next commit). Run: mote-run go test ./internal/memdistill (ok), go vet (ok). Broken by hand, each red then green restored: the quiet check (ReadsQuietSessionsOnce), the read-once mark (three tests), the text-only filter (WhatIsSent), the on switch (OffReadsNothing), skipping gateway-only/own sessions (ReadsQuietSessionsOnce). Not tried: a real model; that comes with the wiring.
This commit is contained in:
@@ -0,0 +1,435 @@
|
||||
// Package memdistill reads the agents' finished conversations and asks a
|
||||
// model what in them is worth remembering: a preference the user stated,
|
||||
// a rule learned from a correction, a fact of the project the code
|
||||
// doesn't say. What it finds waits in memory as a candidate (To review)
|
||||
// until the user keeps it; nothing it proposes reaches an agent before.
|
||||
//
|
||||
// It runs when switched on (State.On), on sessions quiet for Quiet, at
|
||||
// most PerRun of them a run, each once for what it held when read: a
|
||||
// session that goes on is read again later, whole. The model is the one
|
||||
// picked, else the caller's automatic choice. The request goes through
|
||||
// magpie's own gateway (Complete), so masking and routing apply as to any
|
||||
// agent's request.
|
||||
package memdistill
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// Complete sends one request to model: a system text and one user
|
||||
// message, and returns the reply's text.
|
||||
type Complete func(ctx context.Context, model, system, user string) (string, error)
|
||||
|
||||
const (
|
||||
// Quiet is how long a session has had no turn before it is read: one
|
||||
// still going is read when it stops
|
||||
Quiet = 30 * time.Minute
|
||||
// PerRun caps the sessions one run sends to the model
|
||||
PerRun = 10
|
||||
// Back is how far back a run looks the first time it is switched on
|
||||
Back = 7 * 24 * time.Hour
|
||||
// MinTurns is the fewest things the user said for a session to be read
|
||||
MinTurns = 2
|
||||
// MaxPerSession caps what one session may propose
|
||||
MaxPerSession = 5
|
||||
// budget is the transcript's size sent, in characters
|
||||
budget = 24_000
|
||||
// keepMarks is how long a read session's mark is kept
|
||||
keepMarks = 30 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// Agent is the agent id the model requests are made as (gateway.TokenFor),
|
||||
// so Usage counts them apart, and whose sessions are never read.
|
||||
const Agent = "memory"
|
||||
|
||||
// State is distill.json.
|
||||
type State struct {
|
||||
On bool `json:"on,omitempty"`
|
||||
// Model is the model picked; "" is the automatic choice
|
||||
Model string `json:"model,omitempty"`
|
||||
// Since is when it was switched on, less Back: older sessions aren't read
|
||||
Since time.Time `json:"since,omitzero"`
|
||||
// Done is each read session's last turn when it was read, by
|
||||
// agent/id
|
||||
Done map[string]time.Time `json:"done,omitempty"`
|
||||
// the last run: when, with which model, how many sessions read, how
|
||||
// many memories proposed, and what stopped it
|
||||
Last time.Time `json:"last,omitzero"`
|
||||
LastModel string `json:"lastModel,omitempty"`
|
||||
Read int `json:"read,omitempty"`
|
||||
Added int `json:"added,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Path is distill.json; a variable for tests.
|
||||
var Path = func() string { return appdir.Join(appdir.Config(), "distill.json") }
|
||||
|
||||
var (
|
||||
now = time.Now
|
||||
list = func() []sessions.Session { return sessions.List(400) }
|
||||
read = sessions.TranscriptOf
|
||||
// running is held through a run in this process, and the file lock
|
||||
// across magpies
|
||||
running sync.Mutex
|
||||
)
|
||||
|
||||
// ErrRunning is a run asked for while one is going.
|
||||
var ErrRunning = errors.New("already reading conversations")
|
||||
|
||||
// Load reads distill.json; a missing file is the default (off). One that
|
||||
// can't be read is an error, never the default: a run doesn't start, and
|
||||
// a change isn't written over it.
|
||||
func Load() (State, error) {
|
||||
var s State
|
||||
b, err := lastgood.Read(Path(), lastgood.Into[State])
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return s, nil
|
||||
}
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func save(s State) error {
|
||||
b, err := json.MarshalIndent(s, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := Path()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := p + ".tmp"
|
||||
if err := os.WriteFile(tmp, b, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, p); err != nil {
|
||||
return err
|
||||
}
|
||||
return lastgood.Keep(p, lastgood.Into[State], 0o600)
|
||||
}
|
||||
|
||||
// change applies fn to distill.json under its lock.
|
||||
func change(fn func(*State)) (State, error) {
|
||||
unlock, held := filelock.Lock(Path()+".lock", 10*time.Second)
|
||||
if !held {
|
||||
return State{}, errors.New("distill.json is held by another magpie")
|
||||
}
|
||||
defer unlock()
|
||||
s, err := Load()
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
fn(&s)
|
||||
return s, save(s)
|
||||
}
|
||||
|
||||
// Set switches distilling on or off and picks its model ("" automatic).
|
||||
// Switched on from off, it looks back Back from now.
|
||||
func Set(on bool, model string) (State, error) {
|
||||
return change(func(s *State) {
|
||||
if on && !s.On {
|
||||
s.Since = now().Add(-Back).UTC()
|
||||
}
|
||||
s.On, s.Model = on, strings.TrimSpace(model)
|
||||
})
|
||||
}
|
||||
|
||||
// Result is what one run did.
|
||||
type Result struct {
|
||||
Read int
|
||||
Added int
|
||||
}
|
||||
|
||||
// Run reads the sessions due, if switched on, with model when the state
|
||||
// names none. A model that fails stops the run: the sessions not read
|
||||
// yet are read next time.
|
||||
func Run(ctx context.Context, auto string, complete Complete) (Result, error) {
|
||||
if !running.TryLock() {
|
||||
return Result{}, ErrRunning
|
||||
}
|
||||
defer running.Unlock()
|
||||
unlock, held := filelock.Lock(Path()+".run", 0)
|
||||
if !held {
|
||||
return Result{}, ErrRunning
|
||||
}
|
||||
defer unlock()
|
||||
st, err := Load()
|
||||
if err != nil || !st.On {
|
||||
return Result{}, err
|
||||
}
|
||||
model := st.Model
|
||||
if model == "" {
|
||||
model = auto
|
||||
}
|
||||
var res ran
|
||||
var runErr error
|
||||
if model == "" {
|
||||
runErr = errors.New("no model to read conversations with: pick one")
|
||||
} else {
|
||||
res, runErr = run(ctx, st, model, complete)
|
||||
}
|
||||
_, err = change(func(s *State) {
|
||||
s.Last, s.LastModel, s.Read, s.Added, s.Error = now().UTC(), model, res.Read, res.Added, ""
|
||||
if runErr != nil {
|
||||
s.Error = runErr.Error()
|
||||
}
|
||||
if s.Done == nil {
|
||||
s.Done = map[string]time.Time{}
|
||||
}
|
||||
for k, at := range res.done {
|
||||
s.Done[k] = at
|
||||
}
|
||||
for k, at := range s.Done {
|
||||
if now().Sub(at) > keepMarks {
|
||||
delete(s.Done, k)
|
||||
}
|
||||
}
|
||||
})
|
||||
return res.Result, errors.Join(runErr, err)
|
||||
}
|
||||
|
||||
type ran struct {
|
||||
Result
|
||||
done map[string]time.Time
|
||||
}
|
||||
|
||||
// due are the sessions to read now, the latest first.
|
||||
func due(st State, t time.Time) []sessions.Session {
|
||||
var out []sessions.Session
|
||||
for _, s := range list() {
|
||||
switch {
|
||||
case s.Agent == Agent, s.Gateway, s.ReadOnly, !s.Transcript,
|
||||
s.ParentSession != "",
|
||||
t.Sub(s.Last) < Quiet, s.Last.Before(st.Since):
|
||||
continue
|
||||
}
|
||||
if at, ok := st.Done[key(s)]; ok && !s.Last.After(at) {
|
||||
continue
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b sessions.Session) int { return b.Last.Compare(a.Last) })
|
||||
return out
|
||||
}
|
||||
|
||||
func key(s sessions.Session) string { return s.Agent + "/" + s.ID }
|
||||
|
||||
func run(ctx context.Context, st State, model string, complete Complete) (ran, error) {
|
||||
r := ran{done: map[string]time.Time{}}
|
||||
for _, s := range due(st, now()) {
|
||||
if r.Read >= PerRun {
|
||||
break
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return r, ctx.Err()
|
||||
}
|
||||
tr, err := read(s)
|
||||
if err != nil {
|
||||
// one that can't be read now is tried again when it changes
|
||||
r.done[key(s)] = s.Last
|
||||
continue
|
||||
}
|
||||
text, turns := transcript(tr)
|
||||
if turns < MinTurns {
|
||||
r.done[key(s)] = s.Last
|
||||
continue
|
||||
}
|
||||
proj := memory.ProjectOf(s.Cwd)
|
||||
reply, err := complete(ctx, model, prompt, request(text, known(proj), proj))
|
||||
if err != nil {
|
||||
return r, fmt.Errorf("%s: %w", model, err)
|
||||
}
|
||||
r.Read++
|
||||
r.done[key(s)] = s.Last
|
||||
r.Added += keep(parse(reply), s, proj)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// transcript is what was said, user and assistant text alone (no tool
|
||||
// calls, results or thinking), each turn named, within budget: the start
|
||||
// and the end kept when it is longer. turns counts the user's.
|
||||
func transcript(t sessions.Transcript) (string, int) {
|
||||
var lines []string
|
||||
turns := 0
|
||||
for _, p := range t.Parts {
|
||||
if p.Kind != "text" || p.Role != "user" && p.Role != "assistant" {
|
||||
continue
|
||||
}
|
||||
who, max := "User", 4000
|
||||
if p.Role == "assistant" {
|
||||
who, max = "Assistant", 1200
|
||||
} else {
|
||||
turns++
|
||||
}
|
||||
lines = append(lines, who+": "+cut(p.Text, max))
|
||||
}
|
||||
s := strings.Join(lines, "\n\n")
|
||||
if len(s) > budget {
|
||||
head, tail := budget/3, budget-budget/3
|
||||
s = cutBytes(s[:head]) + "\n\n[…]\n\n" + strings.ToValidUTF8(s[len(s)-tail:], "")
|
||||
}
|
||||
return s, turns
|
||||
}
|
||||
|
||||
func cut(s string, max int) string {
|
||||
if utf8.RuneCountInString(s) <= max {
|
||||
return s
|
||||
}
|
||||
return string([]rune(s)[:max]) + "…"
|
||||
}
|
||||
|
||||
func cutBytes(s string) string { return strings.ToValidUTF8(s, "") }
|
||||
|
||||
// known are the memories the model is shown, so it proposes none of them
|
||||
// again: the active and waiting ones everyone has, and the project's.
|
||||
func known(proj *memory.Project) []string {
|
||||
ms, _, err := memory.All()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, m := range ms {
|
||||
if m.Status != memory.Active && m.Status != memory.Candidate {
|
||||
continue
|
||||
}
|
||||
if m.Scope == memory.Global || proj != nil && m.Scope == "project:"+proj.Key {
|
||||
out = append(out, "- "+oneLine(m.Text))
|
||||
}
|
||||
}
|
||||
if len(out) > 80 {
|
||||
out = out[len(out)-80:]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") }
|
||||
|
||||
// prompt names neither the app reading nor any vendor: it goes to the
|
||||
// model's vendor as written.
|
||||
const prompt = `You read a conversation between a user and a coding assistant and write down what is worth remembering in later conversations, with this user or in this project.
|
||||
|
||||
Keep only what stays true beyond this conversation and that a later assistant couldn't learn by reading the code:
|
||||
- profile: who the user is (role, languages they speak, what they know)
|
||||
- preference: how the user wants things done, stated or shown by a correction
|
||||
- rule: a rule learned from a mistake the user corrected, with why
|
||||
- fact: something true of the project that the code doesn't say
|
||||
- reference: where something is (a host, a dashboard, a URL, a document)
|
||||
- procedure: steps that worked for a task likely to come again
|
||||
- episode: a decision that was made, and why
|
||||
|
||||
Leave out: the task itself and its progress, anything about this conversation alone, code details visible in the repository, secrets (keys, tokens, passwords), and anything already in "Already known". When nothing is worth keeping, answer [].
|
||||
|
||||
Answer with a JSON array alone, at most 5 items:
|
||||
[{"text": "one short sentence, in the language the user wrote in", "kind": "preference", "scope": "global or project", "why": "what in the conversation shows it", "quote": "the user's words that show it, short"}]
|
||||
scope is "project" when it holds only in this project, "global" when it holds for the user everywhere.`
|
||||
|
||||
func request(text string, known []string, proj *memory.Project) string {
|
||||
var b strings.Builder
|
||||
if proj != nil {
|
||||
fmt.Fprintf(&b, "Project: %s\n\n", proj.Name)
|
||||
}
|
||||
b.WriteString("Already known:\n")
|
||||
if len(known) == 0 {
|
||||
b.WriteString("(nothing)\n")
|
||||
}
|
||||
for _, k := range known {
|
||||
b.WriteString(k + "\n")
|
||||
}
|
||||
b.WriteString("\nConversation:\n\n")
|
||||
b.WriteString(text)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// found is one memory the model proposed.
|
||||
type found struct {
|
||||
Text string `json:"text"`
|
||||
Kind string `json:"kind"`
|
||||
Scope string `json:"scope"`
|
||||
Why string `json:"why"`
|
||||
Quote string `json:"quote"`
|
||||
}
|
||||
|
||||
// parse reads the reply's JSON array, in a code fence or after words; a
|
||||
// reply without one is nothing found.
|
||||
func parse(reply string) []found {
|
||||
i, j := strings.Index(reply, "["), strings.LastIndex(reply, "]")
|
||||
if i < 0 || j < i {
|
||||
return nil
|
||||
}
|
||||
var out []found
|
||||
if json.Unmarshal([]byte(reply[i:j+1]), &out) != nil {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// keep saves what was found as candidates, each from s, and counts the
|
||||
// new ones. A kind not known is a fact; a project scope without a project
|
||||
// is everyone's.
|
||||
func keep(fs []found, s sessions.Session, proj *memory.Project) int {
|
||||
n := 0
|
||||
for i, f := range fs {
|
||||
if i >= MaxPerSession {
|
||||
break
|
||||
}
|
||||
text := strings.TrimSpace(f.Text)
|
||||
if text == "" || utf8.RuneCountInString(text) > 400 {
|
||||
continue
|
||||
}
|
||||
kind := strings.ToLower(strings.TrimSpace(f.Kind))
|
||||
if !slices.Contains(memory.Kinds, kind) {
|
||||
kind = memory.Fact
|
||||
}
|
||||
scope, p := memory.Global, (*memory.Project)(nil)
|
||||
if strings.EqualFold(strings.TrimSpace(f.Scope), "project") && proj != nil {
|
||||
scope, p = "project:"+proj.Key, proj
|
||||
}
|
||||
why, status := cut(strings.TrimSpace(f.Why), 300), memory.Candidate
|
||||
src := &memory.Source{Agent: s.Agent, Session: s.ID, Dir: s.Cwd, Quote: cut(strings.TrimSpace(f.Quote), 300)}
|
||||
_, added, err := memory.Save(memory.Input{Text: &text, Kind: &kind, Scope: &scope, Why: &why, Status: &status}, memory.FromInferred, src, p)
|
||||
if err == nil && added {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Keep runs Run every interval until ctx ends; auto gives the automatic
|
||||
// model at each run.
|
||||
func Keep(ctx context.Context, interval time.Duration, auto func() string, complete Complete) {
|
||||
t := time.NewTicker(interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
if _, err := Run(ctx, auto(), complete); err != nil && !errors.Is(err, ErrRunning) {
|
||||
log.Println("memory: reading conversations:", err) // and in the Memory tab
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package memdistill
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// sandbox points distill.json and memory.json at the test's own files,
|
||||
// holds the clock, and lists the sessions given, each read as the
|
||||
// transcript named for it.
|
||||
type sandbox struct {
|
||||
at time.Time
|
||||
list []sessions.Session
|
||||
trs map[string]sessions.Transcript
|
||||
asked []string // the sessions the model was asked about, by the first user line
|
||||
reply func(user string) (string, error)
|
||||
dir string
|
||||
}
|
||||
|
||||
func newSandbox(t *testing.T) *sandbox {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
sb := &sandbox{at: time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC), trs: map[string]sessions.Transcript{}, dir: dir}
|
||||
oldPath, oldMem, oldNow, oldList, oldRead := Path, memory.Path, now, list, read
|
||||
Path = func() string { return filepath.Join(dir, "distill.json") }
|
||||
memory.Path = func() string { return filepath.Join(dir, "memory.json") }
|
||||
now = func() time.Time { return sb.at }
|
||||
list = func() []sessions.Session { return sb.list }
|
||||
read = func(s sessions.Session) (sessions.Transcript, error) {
|
||||
tr, ok := sb.trs[s.ID]
|
||||
if !ok {
|
||||
return tr, sessions.ErrNoTranscript
|
||||
}
|
||||
return tr, nil
|
||||
}
|
||||
t.Cleanup(func() { Path, memory.Path, now, list, read = oldPath, oldMem, oldNow, oldList, oldRead })
|
||||
return sb
|
||||
}
|
||||
|
||||
// session adds a readable session of codex's, last active ago, whose
|
||||
// user said each of said.
|
||||
func (sb *sandbox) session(id string, ago time.Duration, said ...string) *sessions.Session {
|
||||
sb.list = append(sb.list, sessions.Session{Agent: "codex", ID: id, Cwd: filepath.Join(sb.dir, "proj"), Last: sb.at.Add(-ago), Transcript: true})
|
||||
var parts []sessions.Part
|
||||
for _, s := range said {
|
||||
parts = append(parts, sessions.Part{Role: "user", Kind: "text", Text: s},
|
||||
sessions.Part{Role: "assistant", Kind: "thinking", Text: "secret thoughts"},
|
||||
sessions.Part{Role: "assistant", Kind: "tool_use", Name: "shell", Text: "rm -rf build"},
|
||||
sessions.Part{Role: "assistant", Kind: "text", Text: "Done."})
|
||||
}
|
||||
sb.trs[id] = sessions.Transcript{Parts: parts}
|
||||
return &sb.list[len(sb.list)-1]
|
||||
}
|
||||
|
||||
func (sb *sandbox) complete(_ context.Context, model, system, user string) (string, error) {
|
||||
_, conv, _ := strings.Cut(user, "Conversation:\n\n")
|
||||
first, _, _ := strings.Cut(conv, "\n")
|
||||
sb.asked = append(sb.asked, model+" "+first)
|
||||
if sb.reply == nil {
|
||||
return "[]", nil
|
||||
}
|
||||
return sb.reply(user)
|
||||
}
|
||||
|
||||
func on(t *testing.T, model string) {
|
||||
t.Helper()
|
||||
if _, err := Set(true, model); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func memories(t *testing.T) []*memory.Memory {
|
||||
t.Helper()
|
||||
ms, _, err := memory.All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
|
||||
// Off by default: nothing is read, and nothing is written.
|
||||
func TestOffReadsNothing(t *testing.T) {
|
||||
sb := newSandbox(t)
|
||||
sb.session("s1", time.Hour, "use pnpm", "always pnpm")
|
||||
if res, err := Run(context.Background(), "auto/m", sb.complete); err != nil || res.Read != 0 || len(sb.asked) != 0 {
|
||||
t.Fatalf("%+v %v %v", res, err, sb.asked)
|
||||
}
|
||||
if _, err := os.Stat(Path()); err == nil {
|
||||
t.Fatal("off, but distill.json was written")
|
||||
}
|
||||
}
|
||||
|
||||
// Only a main session that has been quiet for Quiet, is readable, isn't
|
||||
// magpie's own, said enough and is newer than Since is read; what it
|
||||
// proposes waits as a candidate with where it came from; it isn't read
|
||||
// again until it goes on.
|
||||
func TestReadsQuietSessionsOnce(t *testing.T) {
|
||||
sb := newSandbox(t)
|
||||
on(t, "")
|
||||
sb.session("quiet", time.Hour, "quiet: we deploy with make ship", "never use npm here, pnpm only")
|
||||
sb.session("going", 5*time.Minute, "going: one", "two")
|
||||
sb.session("short", time.Hour, "short: hi")
|
||||
sb.session("sub", time.Hour, "sub: one", "two").ParentSession = "quiet"
|
||||
sb.session("gw", time.Hour, "gw: one", "two").Gateway = true
|
||||
sb.session("old", 8*24*time.Hour, "old: one", "two")
|
||||
sb.session("own", time.Hour, "own: one", "two").Agent = Agent
|
||||
sb.session("unread", time.Hour).Transcript = false
|
||||
sb.reply = func(user string) (string, error) {
|
||||
return "Here they are:\n```json\n" + `[
|
||||
{"text":"Use pnpm, never npm","kind":"rule","scope":"project","why":"said so","quote":"never use npm here, pnpm only"},
|
||||
{"text":"Deploys go out with make ship","kind":"nonsense","scope":"project"},
|
||||
{"text":"Prefers short answers","kind":"preference","scope":"global"},
|
||||
{"text":"","kind":"fact"}
|
||||
]` + "\n```", nil
|
||||
}
|
||||
res, err := Run(context.Background(), "auto/m", sb.complete)
|
||||
if err != nil || res.Read != 1 || res.Added != 3 {
|
||||
t.Fatalf("%+v %v", res, err)
|
||||
}
|
||||
if len(sb.asked) != 1 || sb.asked[0] != "auto/m User: quiet: we deploy with make ship" {
|
||||
t.Fatalf("asked about %q", sb.asked)
|
||||
}
|
||||
ms := memories(t)
|
||||
proj := memory.ProjectOf(filepath.Join(sb.dir, "proj"))
|
||||
want := map[string]string{"Use pnpm, never npm": "rule project:" + proj.Key, "Deploys go out with make ship": "fact project:" + proj.Key, "Prefers short answers": "preference global"}
|
||||
for _, m := range ms {
|
||||
if want[m.Text] != m.Kind+" "+m.Scope || m.Origin != memory.FromInferred || m.Status != memory.Candidate || len(m.Sources) != 1 || m.Sources[0].Session != "quiet" || m.Sources[0].Agent != "codex" {
|
||||
t.Errorf("%+v", m)
|
||||
}
|
||||
delete(want, m.Text)
|
||||
}
|
||||
if len(want) != 0 {
|
||||
t.Fatalf("not kept: %v", want)
|
||||
}
|
||||
for _, m := range ms {
|
||||
if m.Text == "Use pnpm, never npm" && (m.Sources[0].Quote != "never use npm here, pnpm only" || m.Why != "said so") {
|
||||
t.Fatalf("%+v", m)
|
||||
}
|
||||
}
|
||||
st, _ := Load()
|
||||
if st.Read != 1 || st.Added != 3 || st.LastModel != "auto/m" || st.Error != "" {
|
||||
t.Fatalf("%+v", st)
|
||||
}
|
||||
|
||||
// read once
|
||||
if res, err := Run(context.Background(), "auto/m", sb.complete); err != nil || res.Read != 0 || len(sb.asked) != 1 {
|
||||
t.Fatalf("read again: %+v %v %q", res, err, sb.asked)
|
||||
}
|
||||
// it went on: read again, once quiet, with the model picked; the same
|
||||
// memories aren't added twice
|
||||
sb.at = sb.at.Add(time.Hour)
|
||||
sb.list[0].Last = sb.at.Add(-40 * time.Minute)
|
||||
on(t, "picked/m")
|
||||
if res, err := Run(context.Background(), "auto/m", sb.complete); err != nil || res.Read != 2 || res.Added != 0 {
|
||||
t.Fatalf("%+v %v %q", res, err, sb.asked)
|
||||
}
|
||||
if got := sb.asked[1:]; got[0] != "picked/m User: quiet: we deploy with make ship" || got[1] != "picked/m User: going: one" {
|
||||
t.Fatalf("%q", got)
|
||||
}
|
||||
if n := len(memories(t)); n != 3 {
|
||||
t.Fatalf("%d memories", n)
|
||||
}
|
||||
}
|
||||
|
||||
// What the model is sent: the user's and the assistant's words, not
|
||||
// thinking or tool calls; the memories already known; and instructions
|
||||
// that name neither the app nor a vendor.
|
||||
func TestWhatIsSent(t *testing.T) {
|
||||
sb := newSandbox(t)
|
||||
on(t, "")
|
||||
text, kind, scope := "Answers in Chinese", memory.Preference, memory.Global
|
||||
if _, _, err := memory.Save(memory.Input{Text: &text, Kind: &kind, Scope: &scope}, memory.FromUser, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb.session("s", time.Hour, "first", "second")
|
||||
var sys, user string
|
||||
complete := func(_ context.Context, _, s, u string) (string, error) { sys, user = s, u; return "[]", nil }
|
||||
if _, err := Run(context.Background(), "a/m", complete); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, w := range []string{"User: first", "Assistant: Done.", "User: second", "- Answers in Chinese", "Project: proj"} {
|
||||
if !strings.Contains(user, w) {
|
||||
t.Errorf("not sent: %q\n%s", w, user)
|
||||
}
|
||||
}
|
||||
for _, w := range []string{"secret thoughts", "rm -rf"} {
|
||||
if strings.Contains(user, w) {
|
||||
t.Errorf("sent: %q", w)
|
||||
}
|
||||
}
|
||||
for _, w := range []string{"magpie", "claude", "codex", "openai", "anthropic", "gpt", "gemini"} {
|
||||
if strings.Contains(strings.ToLower(sys+strings.Split(user, "Conversation:")[0]), w) {
|
||||
t.Errorf("names %q", w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A long conversation is cut to its start and end within budget, never
|
||||
// mid-rune.
|
||||
func TestLongConversationCut(t *testing.T) {
|
||||
var parts []sessions.Part
|
||||
for i := range 200 {
|
||||
parts = append(parts, sessions.Part{Role: "user", Kind: "text", Text: fmt.Sprintf("turn %d 用中文回答", i)}, sessions.Part{Role: "assistant", Kind: "text", Text: strings.Repeat("长", 3000)})
|
||||
}
|
||||
s, turns := transcript(sessions.Transcript{Parts: parts})
|
||||
if turns != 200 || len(s) > budget+20 || !strings.Contains(s, "turn 0 ") || !strings.Contains(s, "turn 199 ") || !strings.Contains(s, "[…]") || !strings.ContainsRune(s, '长') {
|
||||
t.Fatalf("%d %d", turns, len(s))
|
||||
}
|
||||
if !strings.Contains(s, "…") || strings.ContainsRune(s, '�') {
|
||||
t.Fatal("cut badly")
|
||||
}
|
||||
}
|
||||
|
||||
// A model that fails stops the run and says why; the session is read
|
||||
// next time. At most PerRun are read in one run, the latest first.
|
||||
func TestFailureAndCap(t *testing.T) {
|
||||
sb := newSandbox(t)
|
||||
on(t, "")
|
||||
for i := range PerRun + 2 {
|
||||
sb.session(fmt.Sprint("s", i), time.Hour+time.Duration(i)*time.Minute, fmt.Sprint("n", i), "more")
|
||||
}
|
||||
sb.reply = func(string) (string, error) { return "", errors.New("429 out of allowance") }
|
||||
if _, err := Run(context.Background(), "a/m", sb.complete); err == nil || !strings.Contains(err.Error(), "429") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, _ := Load(); !strings.Contains(st.Error, "a/m: 429 out of allowance") || len(st.Done) != 0 {
|
||||
t.Fatalf("%+v", st)
|
||||
}
|
||||
sb.reply, sb.asked = nil, nil
|
||||
if res, err := Run(context.Background(), "a/m", sb.complete); err != nil || res.Read != PerRun || sb.asked[0] != "a/m User: n0" {
|
||||
t.Fatalf("%+v %v %q", res, err, sb.asked)
|
||||
}
|
||||
if st, _ := Load(); st.Error != "" {
|
||||
t.Fatalf("%+v", st)
|
||||
}
|
||||
if res, _ := Run(context.Background(), "a/m", sb.complete); res.Read != 2 {
|
||||
t.Fatalf("%+v", res)
|
||||
}
|
||||
// no model at all: said, nothing read
|
||||
sb.session("late", time.Hour, "x", "y")
|
||||
if _, err := Run(context.Background(), "", sb.complete); err == nil {
|
||||
t.Fatal("no model, no error")
|
||||
}
|
||||
if st, _ := Load(); !strings.Contains(st.Error, "pick one") {
|
||||
t.Fatalf("%+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
// One the user deleted isn't proposed again from another conversation.
|
||||
func TestDeletedNotProposedAgain(t *testing.T) {
|
||||
sb := newSandbox(t)
|
||||
on(t, "")
|
||||
sb.reply = func(string) (string, error) {
|
||||
return `[{"text":"Likes tabs","kind":"preference","scope":"global"}]`, nil
|
||||
}
|
||||
sb.session("a", time.Hour, "x", "y")
|
||||
if res, err := Run(context.Background(), "a/m", sb.complete); err != nil || res.Added != 1 {
|
||||
t.Fatalf("%+v %v", res, err)
|
||||
}
|
||||
if err := memory.Remove(memories(t)[0].ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb.session("b", time.Hour, "x", "y")
|
||||
if res, err := Run(context.Background(), "a/m", sb.complete); err != nil || res.Read != 1 || res.Added != 0 || len(memories(t)) != 0 {
|
||||
t.Fatalf("%+v %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
// distill.json that can't be read is never written over, and nothing runs.
|
||||
func TestUnreadableStateRunsNothing(t *testing.T) {
|
||||
sb := newSandbox(t)
|
||||
sb.session("s", time.Hour, "x", "y")
|
||||
if err := os.WriteFile(Path(), []byte(`{"on":tru`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Run(context.Background(), "a/m", sb.complete); err == nil || len(sb.asked) != 0 {
|
||||
t.Fatalf("%v %q", err, sb.asked)
|
||||
}
|
||||
if _, err := Set(false, ""); err == nil {
|
||||
t.Fatal("written over")
|
||||
}
|
||||
if b, _ := os.ReadFile(Path()); string(b) != `{"on":tru` {
|
||||
t.Fatalf("%s", b)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user