memory: goes with backups and sync, and suggests what holds everywhere or is a skill (P5)
Backups and sync. memory.json goes in every backup and in the WebDAV, S3 and GitHub sync, under its own toggle (on unless turned off, as the library is). A sync merges memories one by one (memory.Combine): the newer change wins, a memory the user edited or pinned is never taken over by one they didn't, an archived one is kept 30 days and the suggestions turned down are joined. Settings > Sync has a Memory tick, and the description lists memory. Promotion. Library > Memory (In use, no search) shows what memory suggests: a project memory that says the same in two or more projects (the same text, or 60% of its words with 6 or more on each side), or whose sources came from two or more, is offered as global; a procedure searches returned 5 or more times is offered as a skill. Taking a global one keeps the user's own or pinned memory first, then the most used, makes it global and supersedes the rest (into a global with the same text when there is one). Making a skill writes a library skill from its text and why, named from its first words (procedure-<id> for one in Chinese), for the agents ticked for instructions, and archives the memory. A suggestion declined isn't made again, and that goes with sync too. Routes: POST /api/memory/promote, /skill, /decline. Docs: docs/subsystems/memory.md (Backups and sync, Promotion), docs/subsystems/sync-backup.md. Pushed on origin/main14be7f69d, whose 5 commits since8b2fb6b08share no file with this one (not run again). At8b2fb6b08: i18n-keys, library-memory-suggest and webdav-settings-refresh on WSL in both engines, and -run "Memory|Skill|Market|ThirdParty|Promote|Suggest|Sync|Combine" of library, memory and backup on Windows: ok. One rebase before, at origin/main69453574d: go vet of gui, memory, library and -run "Memory|Settings|Parity|Budget|Skill|Promote| Suggest" of gui and memory on Windows: ok; i18n-keys, library-memory*, the five sync files below and sync-own-fields, library-backups-top on WSL in both engines: ok but webkit s3-sync (below). Before the rebase, Go code the same as at the run on the Windows box (xiaomi-gpu, win-run; mote's disk is full, every run there stalled): - go vet ./... (windows) and GOOS=linux go vet -tags nogui ./...: ok. gofmt -l: clean. - go test -count=1 ./internal/memory ./internal/backup ./internal/davsync ./internal/memdistill ./internal/memembed: ok. - ./internal/library: ok but three tests red on Windows that are red the same on origin/maind936be763run alone there and are filed: TestPluginImportCarryOnOffRemove (#6065), TestGoneAgentListedToTakeOut and TestCheckMixedServerEachSide (#4115). -run "Memory|Skill": ok. - ./internal/gui ./internal/cli -run "Memory|Settings|Parity|Budget|Distill|Dream|Skill|Promote|Suggest": ok. GUI on the WSL box (magpie-desktop), chromium and webkit: - library-memory-suggest (new), library-memory, library-memory-select, i18n-keys, sync-own-fields, sync-not-backup, auto-backup, library-backups-top, library-bar-more, login-export, login-import: ok. - every sync-*.test.cjs, github-sync, s3-sync, usage-computers, webdav-settings-refresh, refresh-page, old-webkit: ok but old-webkit's two reds, the same on main and filed (#6030, #5919), and webkit s3-sync's "picking S3 must not scroll the page" (the page is at 0 after the click), red the same on origin/main1ccacad632 of 2 at --test-concurrency=2 one step later ("picking S3 again", #3413). github-sync, s3-sync, sync-signins, sync-other-kind and webdav-settings-refresh were rerun after their expected bodies and descriptions took memory: ok in both engines. Broken by hand: Suggest without the Declined filter turned TestSuggestSkillAndDecline red, and keptFirst without the Fixed order turned TestPromoteKeepsTheUsersOwn red; restored. Not tried: a real sync between two computers with real memory, and the GUI on macOS (mote's disk is full).
This commit is contained in:
@@ -268,13 +268,81 @@ meaning, since it downloads a model (~135 MB).
|
||||
`{on}` give the row its state: the download's progress, the memories
|
||||
read, and why either failed.
|
||||
|
||||
### Backups and sync
|
||||
|
||||
Memory goes to another computer in a backup file (the scheduled backups
|
||||
too) and in sync (WebDAV, S3, GitHub), merged memory by memory, never one
|
||||
computer's memory.json over the other's.
|
||||
[sync.go](../../internal/memory/sync.go) owns it.
|
||||
|
||||
- What goes (`memory.Bundle`, `Collect`): the memories in every state, the
|
||||
projects, the dismissed distilled texts, the suggestions turned down and
|
||||
the deletions. The digest published into the agents' instructions and the
|
||||
vectors (memembed) are this computer's own and are made again after a
|
||||
change. A memory.json that can't be read stops the backup or sync instead
|
||||
of going as no memory (`TestCollectUnreadableIsAnError`,
|
||||
`TestCollectStopsOnUnreadableMemory`).
|
||||
- Merging (`Combine`, the same either way round): of two copies of one
|
||||
memory, the one changed later stays, unless that change wasn't the user's
|
||||
(`Edited` is when the user last changed it) and the other copy is pinned
|
||||
or the user's while it isn't: an agent's forget or a tidy on one computer
|
||||
never undoes a pin made on another (`TestSyncMachineChangeNeverOverUsersOwn`).
|
||||
`Used` and `Uses` are the most of both, and leave `Hash` alone, so a
|
||||
search is no change to push (`TestSyncKeepsMostUses`).
|
||||
- Deleting: `Remove`, and Untidy's delete of a merged memory, note the id
|
||||
in `removed` for 180 days (`keepRemoved`), so a computer that still has
|
||||
it doesn't bring it back; a copy changed after the deletion stays
|
||||
(`TestSyncDeletionStaysDeleted`, `TestSyncEditAfterDeletionKeepsIt`).
|
||||
- Switches: sync's **Memory** tick (`davsync.Config.Memory`, on unless
|
||||
turned off, since a sync file is always sealed with a passphrase), and
|
||||
Export's **With memory** and Import's **Bring in memory too**, both on.
|
||||
A computer with the tick off sends none and takes none, and leaves the
|
||||
server's copy as it was (`TestSyncMemory`, `TestBackupMergesMemory`).
|
||||
- After a sync or restore changes memory, `library.PublishMemory` writes the
|
||||
digests again.
|
||||
|
||||
### Promotion
|
||||
|
||||
Memory suggests making more of what it holds
|
||||
([promote.go](../../internal/memory/promote.go)). The suggestions sit
|
||||
over the In use list, unsearched and not narrowed to a scope
|
||||
(`memSuggestions` in the library plugin's client.js), and come with
|
||||
`GET /api/memory` (`suggestions`).
|
||||
|
||||
- To hold everywhere (`ToGlobal`): active project memories that say the
|
||||
same in two or more projects. The same means the same text (`norm`), or
|
||||
at least 60% of their words in common with six words or more on each
|
||||
side (`sameWords`); two short texts sharing words are as often two
|
||||
facts. A memory whose sources' folders (`Source.Dir`, by the projects'
|
||||
roots) are in two projects counts for both. Taken (`Promote`,
|
||||
`POST /api/memory/promote`), the one kept first (the user's own or
|
||||
pinned, the most used, the latest) becomes global and the others are
|
||||
superseded by it, their tags, sources and uses carried over; a global
|
||||
memory with the same text already is the one kept. It is the user's
|
||||
change, so a sync keeps it (`TestPromoteKeepsTheUsersOwn`,
|
||||
`TestPromoteIntoTheGlobalOne`, `TestSuggestGlobalAcrossProjects`,
|
||||
`TestSuggestGlobalBySourceFolder`).
|
||||
- To be a skill (`ToSkill`): an active procedure that searches returned
|
||||
five times or more (`skillUses`). Taken (`library.MemorySkill`,
|
||||
`POST /api/memory/skill`), it becomes a skill of the library's own: a
|
||||
SKILL.md with the first line as its description, named from its first
|
||||
words (from its id when it has fewer than two Latin words), given to the
|
||||
agents ticked for instructions, or to every agent with skills when none
|
||||
is. The memory is archived then, noted with the skill's name
|
||||
(`MadeSkill`), so it isn't in the digest beside the skill
|
||||
(`TestMemorySkill`, `TestSuggestSkillAndDecline`).
|
||||
- Turned down (`Decline`, `POST /api/memory/decline`): the key goes in
|
||||
`declined` (the last 500), which goes with sync, so it isn't suggested
|
||||
on another computer either. A global suggestion's key is its memories'
|
||||
ids, so another project joining it is a new suggestion.
|
||||
|
||||
## Verification
|
||||
|
||||
```sh
|
||||
mote-run go test ./internal/memory ./internal/memdistill ./internal/memembed ./internal/library
|
||||
mote-run go test ./internal/memory ./internal/backup ./internal/davsync ./internal/memdistill ./internal/memembed ./internal/library
|
||||
mote-run sh -c 'MAGPIE_EMBED_DIR=$HOME/models/pml go test -run Embedder ./internal/pii/guard'
|
||||
mote-run go test -run 'Distill|Dream' ./internal/gui
|
||||
mote-run go test -tags nogui -run 'MemoryMCP|OwnMCP' ./internal/gateway
|
||||
mote-run go test ./internal/browsermcp ./internal/cli
|
||||
mote-run node --test internal/gui/tests/library-memory.test.cjs internal/gui/tests/library-memory-select.test.cjs
|
||||
mote-run node --test internal/gui/tests/library-memory.test.cjs internal/gui/tests/library-memory-select.test.cjs internal/gui/tests/library-memory-suggest.test.cjs
|
||||
```
|
||||
|
||||
@@ -223,6 +223,9 @@ clock.
|
||||
`auto-backup.test.cjs`).
|
||||
- **Sign-ins:** off unless picked (`SignIns`, with `Passphrase`); see
|
||||
[Sign-ins, when picked](#sign-ins-when-picked).
|
||||
- **Memory:** on unless turned off (`Memory`), merged memory by memory in
|
||||
`syncOnce` after the sign-ins, never replaced as a part; see
|
||||
[Memory's backups and sync](memory.md#backups-and-sync).
|
||||
|
||||
## Data folder on another disk
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -33,6 +34,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/profile"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -106,6 +108,10 @@ type Bundle struct {
|
||||
// with their credentials: only when the user asked for them
|
||||
// (WithSignIns). Nil otherwise, and from a magpie before them.
|
||||
SignIns *provider.SignIns `json:"signIns,omitempty"`
|
||||
// Memory is what the agents know (memory.Collect): merged where it is
|
||||
// put back, memory by memory, never put over what is there. Nil from
|
||||
// a magpie before it, or with no memory.
|
||||
Memory *memory.Bundle `json:"memory,omitempty"`
|
||||
}
|
||||
|
||||
// WithSignIns puts this computer's sign-ins in b. One that can't be read
|
||||
@@ -284,6 +290,10 @@ func Collect(keys bool, app string) (Bundle, error) {
|
||||
if !keys && b.Library != nil {
|
||||
b.Library.WithoutSecrets(Secret)
|
||||
}
|
||||
// a memory.json that can't be read stops it too: unknown, not none
|
||||
if b.Memory, err = memory.Collect(); err != nil {
|
||||
return b, fmt.Errorf("memory: %w", err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
@@ -402,10 +412,13 @@ type Parts struct {
|
||||
// SignIns puts the backup's sign-ins in, when it has them
|
||||
// (provider.RestoreSignIns: nothing renewed later here is written over).
|
||||
SignIns bool
|
||||
// Memory merges the backup's memory into this computer's
|
||||
// (memory.Put): a memory here is never taken away by it.
|
||||
Memory bool
|
||||
}
|
||||
|
||||
// All is every part.
|
||||
var All = Parts{Providers: true, Settings: true, Profiles: true, Agents: true, Library: true, SignIns: true}
|
||||
var All = Parts{Providers: true, Settings: true, Profiles: true, Agents: true, Library: true, SignIns: true, Memory: true}
|
||||
|
||||
// Result says what a restore did.
|
||||
type Result struct {
|
||||
@@ -423,6 +436,7 @@ type Result struct {
|
||||
Agents int // agent fields changed
|
||||
Skipped []string // agent fields left alone: the agent is not on this machine, or the value failed
|
||||
Library bool // the library was put in
|
||||
Memory bool `json:",omitempty"` // memory changed: the backup's merged in
|
||||
LibraryProblems []library.Problem `json:",omitempty"` // what of it couldn't be given to an agent
|
||||
// SignIns is what putting the backup's sign-ins in did; nil when it
|
||||
// had none, or they weren't asked for.
|
||||
@@ -614,6 +628,19 @@ func Restore(b Bundle, parts Parts) (Result, error) {
|
||||
}
|
||||
r.Library, r.LibraryProblems = true, res.Problems
|
||||
}
|
||||
if parts.Memory && b.Memory != nil {
|
||||
changed, err := memory.Put(b.Memory)
|
||||
if err != nil {
|
||||
return r, fmt.Errorf("memory: %w", err)
|
||||
}
|
||||
if r.Memory = changed; changed {
|
||||
// the agents' instructions given what came, as after a change
|
||||
// the user made to memory
|
||||
if _, err := library.PublishMemory(false); err != nil {
|
||||
log.Printf("backup: memory digest: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
)
|
||||
|
||||
func saveMemory(t *testing.T, text string) *memory.Memory {
|
||||
t.Helper()
|
||||
k, s := memory.Preference, memory.Global
|
||||
m, _, err := memory.Save(memory.Input{Text: &text, Kind: &k, Scope: &s}, memory.FromUser, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func memoryTexts(t *testing.T) []string {
|
||||
t.Helper()
|
||||
all, _, err := memory.All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out []string
|
||||
for _, m := range all {
|
||||
out = append(out, m.Text)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A backup carries memory, and putting it back merges it with what is
|
||||
// here: a memory only this computer has stays.
|
||||
func TestBackupMergesMemory(t *testing.T) {
|
||||
home(t)
|
||||
saveMemory(t, "Replies in Chinese")
|
||||
b, err := Collect(false, "test") // a backup without keys still has it
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sealed, err := Seal(b, "pass")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
home(t) // another computer
|
||||
saveMemory(t, "Builds run on mote")
|
||||
opened, err := Open(sealed, "pass")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := Restore(opened, Parts{Memory: true})
|
||||
if err != nil || !r.Memory {
|
||||
t.Fatalf("restore: %+v, %v", r, err)
|
||||
}
|
||||
if got := strings.Join(memoryTexts(t), "|"); !strings.Contains(got, "Replies in Chinese") || !strings.Contains(got, "Builds run on mote") {
|
||||
t.Fatalf("memory after the restore: %s", got)
|
||||
}
|
||||
// put back again: nothing changes
|
||||
if r, err := Restore(opened, Parts{Memory: true}); err != nil || r.Memory {
|
||||
t.Fatalf("a second restore changed memory: %+v, %v", r, err)
|
||||
}
|
||||
// left out when not asked for
|
||||
home(t)
|
||||
if _, err := Restore(opened, Parts{Library: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := memoryTexts(t); len(got) != 0 {
|
||||
t.Fatalf("memory put in unasked: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A memory.json that can't be read stops the backup: carried as no
|
||||
// memory, it would say there was none.
|
||||
func TestCollectStopsOnUnreadableMemory(t *testing.T) {
|
||||
home(t)
|
||||
saveMemory(t, "kept")
|
||||
if b, err := Collect(true, "test"); err != nil || b.Memory == nil || len(b.Memory.Memories) != 1 {
|
||||
t.Fatalf("collect: %+v, %v", b.Memory, err)
|
||||
}
|
||||
if err := os.WriteFile(memory.Path(), []byte(`{"memories":[{"id":"m_1`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.Remove(lastgood.Bak(memory.Path()))
|
||||
if _, err := Collect(true, "test"); err == nil || !strings.Contains(err.Error(), "memory") {
|
||||
t.Fatalf("Collect read a memory.json that can't be read: %v", err)
|
||||
}
|
||||
// and no memory.json is no memory, not an error
|
||||
os.Remove(memory.Path())
|
||||
if b, err := Collect(true, "test"); err != nil || b.Memory != nil {
|
||||
t.Fatalf("no memory.json: %+v, %v", b.Memory, err)
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/profile"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -81,6 +82,10 @@ type Config struct {
|
||||
// Library is whether the library goes too; nil, as in a setup made
|
||||
// before it could, is yes
|
||||
Library *bool `json:"library,omitempty"`
|
||||
// Memory is whether memory goes too (memory.Combine says how two
|
||||
// computers' are merged); nil, as in a setup made before it could,
|
||||
// is yes
|
||||
Memory *bool `json:"memory,omitempty"`
|
||||
// Usage is whether this computer shares its usage with the others
|
||||
// syncing to the server, and sees theirs (#542)
|
||||
Usage bool `json:"usage,omitempty"`
|
||||
@@ -171,6 +176,8 @@ func (old Config) saved(c Config) Config {
|
||||
|
||||
func (c Config) library() bool { return c.Library == nil || *c.Library }
|
||||
|
||||
func (c Config) memoryOn() bool { return c.Memory == nil || *c.Memory }
|
||||
|
||||
// S3 is whether c keeps the file in an S3 bucket rather than a WebDAV folder.
|
||||
func (c Config) S3() bool {
|
||||
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(c.URL)), "s3://")
|
||||
@@ -503,6 +510,7 @@ type View struct {
|
||||
PathStyle bool `json:"pathStyle,omitempty"`
|
||||
Branch string `json:"branch,omitempty"`
|
||||
Library bool `json:"library"`
|
||||
Memory bool `json:"memory"`
|
||||
Usage bool `json:"usage,omitempty"`
|
||||
SignIns bool `json:"signIns,omitempty"`
|
||||
// UsageError is why usage couldn't be shared the last time it was tried
|
||||
@@ -550,11 +558,11 @@ type OtherView struct {
|
||||
func Status() View {
|
||||
c, ok := Load()
|
||||
if !ok {
|
||||
return View{Keys: true, Agents: true, Library: true}
|
||||
return View{Keys: true, Agents: true, Library: true, Memory: true}
|
||||
}
|
||||
st := loadState()
|
||||
v := View{On: true, URL: c.URL, User: c.User, PasswordSet: c.Password != "", PassphraseSet: c.Passphrase != "",
|
||||
Keys: c.Keys, Agents: c.Agents, Library: c.library(), Error: st.Error, Notice: st.Notice,
|
||||
Keys: c.Keys, Agents: c.Agents, Library: c.library(), Memory: c.memoryOn(), Error: st.Error, Notice: st.Notice,
|
||||
Kind: strings.ToLower(c.Kind()), Endpoint: c.Endpoint, Region: c.Region, PathStyle: c.PathStyle, Branch: c.Branch,
|
||||
Auto: int(c.auto() / time.Minute), FollowServer: c.FollowServer}
|
||||
if st.Key == stateKey(c) {
|
||||
@@ -839,6 +847,9 @@ func collect(c Config) (backup.Bundle, error) {
|
||||
if !c.library() {
|
||||
b.Library = nil
|
||||
}
|
||||
if !c.memoryOn() {
|
||||
b.Memory = nil
|
||||
}
|
||||
if err == nil && c.SignIns {
|
||||
if serr := backup.WithSignIns(&b); serr != nil {
|
||||
return b, fmt.Errorf("the sign-ins couldn't be read: %w", serr)
|
||||
@@ -904,6 +915,9 @@ func hashes(b backup.Bundle) map[string]string {
|
||||
if b.SignIns != nil { // as before them, without them
|
||||
out["signins"] = h(b.SignIns.Hashes())
|
||||
}
|
||||
if b.Memory != nil { // as before it, without it
|
||||
out["memory"] = b.Memory.Hash()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -1501,10 +1515,29 @@ func syncOnce(ctx context.Context, c Config, st *state) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
// memory, when it goes: merged memory by memory (memory.Combine),
|
||||
// what the server has put in here, and both sides' going up
|
||||
if c.memoryOn() && (local.Memory != nil || remote.Memory != nil) {
|
||||
merged.Memory = memory.Combine(local.Memory, remote.Memory)
|
||||
changed, err := memory.Put(remote.Memory)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bringing in memory: %w", err)
|
||||
}
|
||||
if changed {
|
||||
// the agents' instructions given what came, as after a change
|
||||
// the user made to memory
|
||||
if _, err := library.PublishMemory(false); err != nil {
|
||||
log.Printf("sync: memory digest: %v", err)
|
||||
}
|
||||
if local, err = collect(c); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
now := hashesOwn(local, afterW)
|
||||
M, pending := hashesOwn(merged, afterW), map[string]string{}
|
||||
for _, p := range append(slices.Clone(Parts), "signins") {
|
||||
if _, ok := now[p]; !ok && p == "signins" {
|
||||
for _, p := range append(slices.Clone(Parts), "signins", "memory") {
|
||||
if _, ok := now[p]; !ok && (p == "signins" || p == "memory") {
|
||||
continue
|
||||
}
|
||||
pending[p] = now[p]
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package davsync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
)
|
||||
|
||||
// Memory in sync: what one computer's agents learned is known on the
|
||||
// other, merged memory by memory, a memory deleted on one goes from the
|
||||
// other and doesn't come back, and with the switch off none goes.
|
||||
func TestSyncMemory(t *testing.T) {
|
||||
fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}}
|
||||
srv := httptest.NewServer(fake)
|
||||
defer srv.Close()
|
||||
cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse"}
|
||||
now := func(t *testing.T) {
|
||||
t.Helper()
|
||||
if err := Now(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := Status(); v.Error != "" {
|
||||
t.Fatal(v.Error)
|
||||
}
|
||||
}
|
||||
save := func(t *testing.T, text string) *memory.Memory {
|
||||
t.Helper()
|
||||
k, s := memory.Preference, memory.Global
|
||||
m, _, err := memory.Save(memory.Input{Text: &text, Kind: &k, Scope: &s}, memory.FromAgent, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
have := func(t *testing.T) []string {
|
||||
t.Helper()
|
||||
all, _, err := memory.All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out []string
|
||||
for _, m := range all {
|
||||
out = append(out, m.Text)
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
want := func(t *testing.T, w ...string) {
|
||||
t.Helper()
|
||||
if got := have(t); !slices.Equal(got, w) {
|
||||
t.Fatalf("memory here: %q, want %q", got, w)
|
||||
}
|
||||
}
|
||||
|
||||
a, b := newComputer(t), newComputer(t)
|
||||
a.use(t)
|
||||
m := save(t, "Replies in Chinese")
|
||||
if err := Configure(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now(t)
|
||||
fake.mu.Lock()
|
||||
sealed := string(fake.files["/dav/magpie/magpie.magpie-backup"])
|
||||
fake.mu.Unlock()
|
||||
if strings.Contains(sealed, "Replies in Chinese") {
|
||||
t.Fatal("a memory on the server in the clear")
|
||||
}
|
||||
if v := Status(); !v.Memory {
|
||||
t.Fatal("memory doesn't go by default")
|
||||
}
|
||||
|
||||
b.use(t)
|
||||
save(t, "Builds run on mote")
|
||||
if err := Configure(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now(t)
|
||||
want(t, "Builds run on mote", "Replies in Chinese") // joining: both, neither lost
|
||||
|
||||
a.use(t)
|
||||
now(t)
|
||||
want(t, "Builds run on mote", "Replies in Chinese")
|
||||
|
||||
// deleted on a: gone from b, and not brought back to a by b
|
||||
if err := memory.Remove(m.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now(t)
|
||||
b.use(t)
|
||||
now(t)
|
||||
want(t, "Builds run on mote")
|
||||
a.use(t)
|
||||
now(t)
|
||||
want(t, "Builds run on mote")
|
||||
|
||||
// switched off on b: what b learns next stays on b
|
||||
b.use(t)
|
||||
off := false
|
||||
c := cfg
|
||||
c.Memory = &off
|
||||
if err := Configure(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
save(t, "Only on b")
|
||||
now(t)
|
||||
a.use(t)
|
||||
now(t)
|
||||
want(t, "Builds run on mote")
|
||||
// and a's memory still reaches the server through a
|
||||
save(t, "Learned on a")
|
||||
now(t)
|
||||
b.use(t)
|
||||
now(t)
|
||||
want(t, "Builds run on mote", "Only on b") // off: nothing comes either
|
||||
}
|
||||
@@ -20286,12 +20286,13 @@ async function renderSync(v) {
|
||||
};
|
||||
const btn = (label, fn, cls = "text") => { const b = el("button", cls, label); b.onclick = fn; return b; };
|
||||
const toggle = (id) => () => { syncOpen = syncOpen === id ? "" : id; renderSync(); };
|
||||
const parts = (ps) => ps.map((p) => t({ providers: "providers", settings: "settings", profiles: "profiles", agents: "agents' models", library: "library", usage: "usage", signins: "sign-ins" }[p])).join(t(", "));
|
||||
const parts = (ps) => ps.map((p) => t({ providers: "providers", settings: "settings", profiles: "profiles", agents: "agents' models", library: "library", memory: "memory", usage: "usage", signins: "sign-ins" }[p])).join(t(", "));
|
||||
|
||||
// off: what it would keep the same, from the view's toggles (none: all on)
|
||||
const goes = ["settings", "profiles"];
|
||||
if (v.agents !== false) goes.push("agents");
|
||||
if (v.library !== false) goes.push("library");
|
||||
if (v.memory !== false) goes.push("memory");
|
||||
if (v.usage) goes.push("usage");
|
||||
if (v.signIns) goes.push("signins");
|
||||
let line = t("Keeps {parts} the same on every computer", {
|
||||
|
||||
@@ -3264,6 +3264,9 @@ const I18N = {
|
||||
"With the sign-ins: subscription accounts and plugin sign-ins": "包含登录信息:订阅账号和插件的登录",
|
||||
"Needed to open the file. The sign-ins are in it: anyone with the file and the passphrase can use those accounts, so pick a strong one.": "打开文件时需要。文件里有登录信息:拿到文件和口令的人就能使用这些账号,请设一个够强的口令。",
|
||||
"Bring in the sign-ins too, when the file has them": "文件里有登录信息时,也一并导入",
|
||||
"Memory: what the agents know, merged memory by memory": "记忆:agent 记住的内容,逐条合并",
|
||||
"With memory: what the agents know": "包含记忆:agent 记住的内容",
|
||||
"Bring in memory too, merged with the memories here": "也导入记忆,与本机的记忆合并",
|
||||
"This backup's settings use {names}, which isn't signed in on this computer, and the backup has no sign-in for it. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "这个备份的设置用到了 {names},本机没有登录,备份里也没有它的登录信息。要在这里使用,请在「服务商 → 添加服务商」中登录;不用的话无需处理。",
|
||||
"Sign-ins: {added} added, {updated} updated, {kept} kept as they are here": "登录信息:新增 {added} 个,更新 {updated} 个,{kept} 个保持本机的",
|
||||
"One kept as it is here was renewed later here, or is the account the agent itself is signed in with.": "保持本机的账号:本机的续期时间更晚,或是智能体自己登录着的账号。",
|
||||
@@ -8284,6 +8287,9 @@ const I18N = {
|
||||
"With the sign-ins: subscription accounts and plugin sign-ins": "包含登入資訊:訂閱帳號和外掛的登入",
|
||||
"Needed to open the file. The sign-ins are in it: anyone with the file and the passphrase can use those accounts, so pick a strong one.": "開啟檔案時需要。檔案裡有登入資訊:拿到檔案和口令的人就能使用這些帳號,請設一個夠強的口令。",
|
||||
"Bring in the sign-ins too, when the file has them": "檔案裡有登入資訊時,也一併匯入",
|
||||
"Memory: what the agents know, merged memory by memory": "記憶:agent 記住的內容,逐條合併",
|
||||
"With memory: what the agents know": "包含記憶:agent 記住的內容",
|
||||
"Bring in memory too, merged with the memories here": "也匯入記憶,與本機的記憶合併",
|
||||
"This backup's settings use {names}, which isn't signed in on this computer, and the backup has no sign-in for it. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "這個備份的設定用到了 {names},本機沒有登入,備份裡也沒有它的登入資訊。要在這裡使用,請在「服務商 → 新增服務商」中登入;不用的話無需處理。",
|
||||
"Sign-ins: {added} added, {updated} updated, {kept} kept as they are here": "登入資訊:新增 {added} 個,更新 {updated} 個,{kept} 個保持本機的",
|
||||
"One kept as it is here was renewed later here, or is the account the agent itself is signed in with.": "保持本機的帳號:本機的續期時間更晚,或是代理自己登入著的帳號。",
|
||||
@@ -13317,6 +13323,9 @@ const I18N = {
|
||||
"With the sign-ins: subscription accounts and plugin sign-ins": "サインインも含める:サブスクリプションのアカウントとプラグインのサインイン",
|
||||
"Needed to open the file. The sign-ins are in it: anyone with the file and the passphrase can use those accounts, so pick a strong one.": "ファイルを開くのに必要です。サインインが含まれます:ファイルとパスフレーズを持つ人は誰でもそれらのアカウントを使えるので、強いものを選んでください。",
|
||||
"Bring in the sign-ins too, when the file has them": "ファイルにサインインがあれば、それも取り込む",
|
||||
"Memory: what the agents know, merged memory by memory": "メモリー:エージェントが覚えていること、1 件ずつマージ",
|
||||
"With memory: what the agents know": "メモリーも含める:エージェントが覚えていること",
|
||||
"Bring in memory too, merged with the memories here": "メモリーも取り込み、このコンピューターのメモリーとマージする",
|
||||
"This backup's settings use {names}, which isn't signed in on this computer, and the backup has no sign-in for it. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "このバックアップの設定は {names} を使いますが、このコンピューターではサインインしておらず、バックアップにもそのサインインはありません。ここで使うには「プロバイダ → プロバイダを追加」でサインインしてください。使わないなら何もする必要はありません。",
|
||||
"Sign-ins: {added} added, {updated} updated, {kept} kept as they are here": "サインイン:{added} 件追加、{updated} 件更新、{kept} 件はここのまま",
|
||||
"One kept as it is here was renewed later here, or is the account the agent itself is signed in with.": "ここのままにしたものは、ここでの更新のほうが新しいか、エージェント自身がサインインしているアカウントです。",
|
||||
@@ -18359,6 +18368,9 @@ const I18N = {
|
||||
"With the sign-ins: subscription accounts and plugin sign-ins": "Mit den Anmeldungen: Abo-Konten und Plugin-Anmeldungen",
|
||||
"Needed to open the file. The sign-ins are in it: anyone with the file and the passphrase can use those accounts, so pick a strong one.": "Zum Öffnen der Datei nötig. Die Anmeldungen sind darin: Wer die Datei und die Passphrase hat, kann diese Konten nutzen, wähle also eine starke.",
|
||||
"Bring in the sign-ins too, when the file has them": "Auch die Anmeldungen übernehmen, wenn die Datei welche hat",
|
||||
"Memory: what the agents know, merged memory by memory": "Gedächtnis: was die Agenten wissen, Eintrag für Eintrag zusammengeführt",
|
||||
"With memory: what the agents know": "Mit dem Gedächtnis: was die Agenten wissen",
|
||||
"Bring in memory too, merged with the memories here": "Auch das Gedächtnis übernehmen, mit dem hiesigen zusammengeführt",
|
||||
"This backup's settings use {names}, which isn't signed in on this computer, and the backup has no sign-in for it. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "Die Einstellungen dieses Backups nutzen {names}, das auf diesem Computer nicht angemeldet ist, und das Backup hat keine Anmeldung dafür. Um es hier zu nutzen, melde dich unter Anbieter → Anbieter hinzufügen an; sonst ist nichts zu tun.",
|
||||
"Sign-ins: {added} added, {updated} updated, {kept} kept as they are here": "Anmeldungen: {added} hinzugefügt, {updated} aktualisiert, {kept} wie hier belassen",
|
||||
"One kept as it is here was renewed later here, or is the account the agent itself is signed in with.": "Ein hier belassenes Konto wurde hier später erneuert oder ist das Konto, mit dem der Agent selbst angemeldet ist.",
|
||||
|
||||
@@ -1122,6 +1122,7 @@ magpie.plugin("library", (ctx) => {
|
||||
bar.append(button("+ " + t("Add"), "action lib-memadd", () => { endMemPick(); openMemory(null); render(); }));
|
||||
body.append(bar);
|
||||
|
||||
if (memStatus === "active" && !words.length && !memScope && !memPicking && (mem.suggestions || []).length) body.append(memSuggestions());
|
||||
const list = el("div", "list lib-list lib-mems" + (memPicking ? " picking" : ""));
|
||||
if (memOpen === "new") list.append(memDetail(null));
|
||||
for (const m of shown) list.append(...memRow(m));
|
||||
@@ -1135,6 +1136,31 @@ magpie.plugin("library", (ctx) => {
|
||||
if (memPicking) body.append(memPickBar());
|
||||
}
|
||||
|
||||
// what memory suggests (memory.Suggest): a memory learned in several
|
||||
// projects to hold everywhere, a procedure searched for often to be a
|
||||
// skill; each taken or turned down for good
|
||||
function memSuggestions() {
|
||||
const list = el("div", "list lib-list lib-memsugg");
|
||||
for (const s of mem.suggestions) {
|
||||
const r = el("div", "row lib-row");
|
||||
r.dataset.sugg = s.key;
|
||||
const w = el("div", "who");
|
||||
w.append(el("div", "name", s.text));
|
||||
const acts = el("div", "lib-acts");
|
||||
if (s.to === "global") {
|
||||
w.append(el("div", "sub", t("Learned in {projects}", { projects: s.projects.map((k) => mem.projects?.[k]?.name || k).join(", ") })));
|
||||
acts.append(button(t("Use everywhere"), "action", () => memChange("memory/promote", { ids: s.ids }, t("It holds everywhere now"))));
|
||||
} else {
|
||||
w.append(el("div", "sub", t("Searched {n} times", { n: s.uses })));
|
||||
acts.append(button(t("Make a skill"), "action", async () => { if (await memChange("memory/skill", { id: s.ids[0] }, t("It is a skill in the library now"))) load(true); }));
|
||||
}
|
||||
acts.append(button(t("Not now"), "action", () => memChange("memory/decline", { key: s.key })));
|
||||
r.append(glyph(s.to === "global" ? GLYPH.web : GLYPH.skill), w, acts);
|
||||
list.append(r);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// ---------- some memories, picked, acted on at once ----------
|
||||
|
||||
function endMemPick() {
|
||||
|
||||
@@ -3,6 +3,12 @@
|
||||
magpie.strings({
|
||||
zh: {
|
||||
"Stop picking memories": "不再选择记忆",
|
||||
"Learned in {projects}": "在 {projects} 中学到",
|
||||
"Use everywhere": "在所有项目中使用",
|
||||
"It holds everywhere now": "现在对所有项目生效",
|
||||
"Searched {n} times": "被搜索 {n} 次",
|
||||
"Make a skill": "做成 Skill",
|
||||
"It is a skill in the library now": "已作为 Skill 加入资源库",
|
||||
"Pick some memories and act on them together": "选几条记忆,一起处理",
|
||||
"Shift-click picks a range": "按住 Shift 点击可选一段",
|
||||
"{n} kept": "已保留 {n} 条",
|
||||
@@ -966,6 +972,12 @@ magpie.strings({
|
||||
},
|
||||
"zh-TW": {
|
||||
"Stop picking memories": "不再選擇記憶",
|
||||
"Learned in {projects}": "在 {projects} 中學到",
|
||||
"Use everywhere": "在所有專案中使用",
|
||||
"It holds everywhere now": "現在對所有專案生效",
|
||||
"Searched {n} times": "被搜尋 {n} 次",
|
||||
"Make a skill": "做成 Skill",
|
||||
"It is a skill in the library now": "已作為 Skill 加入資源庫",
|
||||
"Pick some memories and act on them together": "選幾條記憶,一起處理",
|
||||
"Shift-click picks a range": "按住 Shift 點擊可選一段",
|
||||
"{n} kept": "已保留 {n} 條",
|
||||
@@ -1929,6 +1941,12 @@ magpie.strings({
|
||||
},
|
||||
ja: {
|
||||
"Stop picking memories": "メモリの選択を終える",
|
||||
"Learned in {projects}": "{projects} で学んだこと",
|
||||
"Use everywhere": "すべてのプロジェクトで使う",
|
||||
"It holds everywhere now": "すべてのプロジェクトで有効になりました",
|
||||
"Searched {n} times": "{n} 回検索されました",
|
||||
"Make a skill": "スキルにする",
|
||||
"It is a skill in the library now": "ライブラリのスキルになりました",
|
||||
"Pick some memories and act on them together": "いくつかのメモリを選んでまとめて操作する",
|
||||
"Shift-click picks a range": "Shift クリックで範囲を選択",
|
||||
"{n} kept": "{n} 件を残しました",
|
||||
@@ -2892,6 +2910,12 @@ magpie.strings({
|
||||
},
|
||||
de: {
|
||||
"Stop picking memories": "Keine Erinnerungen mehr auswählen",
|
||||
"Learned in {projects}": "Gelernt in {projects}",
|
||||
"Use everywhere": "Überall verwenden",
|
||||
"It holds everywhere now": "Gilt jetzt überall",
|
||||
"Searched {n} times": "{n}-mal gesucht",
|
||||
"Make a skill": "Als Skill anlegen",
|
||||
"It is a skill in the library now": "Ist jetzt ein Skill in der Bibliothek",
|
||||
"Pick some memories and act on them together": "Mehrere Erinnerungen auswählen und gemeinsam bearbeiten",
|
||||
"Shift-click picks a range": "Shift-Klick wählt einen Bereich",
|
||||
"{n} kept": "{n} behalten",
|
||||
|
||||
@@ -35,6 +35,7 @@ window.davForm = function (v) {
|
||||
const [keysL, keys] = tick(t("Providers' API keys"), v.keys !== false);
|
||||
const [agentsL, agents] = tick(t("Agents' models"), v.agents !== false);
|
||||
const [libL, lib] = tick(t("Library: instructions, MCP servers, skills, hooks and subagents"), v.library !== false);
|
||||
const [memL, mem] = tick(t("Memory: what the agents know, merged memory by memory"), v.memory !== false);
|
||||
// usage: off unless picked, each computer its own (#542)
|
||||
const [useL, use] = tick(t("Usage: this computer's calls, for the Usage page on the others"), !!v.usage);
|
||||
// sign-ins: off unless picked, sealed with the passphrase like the rest
|
||||
@@ -44,7 +45,7 @@ window.davForm = function (v) {
|
||||
siSay.hidden = !si.checked;
|
||||
si.onchange = () => { siSay.hidden = !si.checked; };
|
||||
const what = el("div", "stack");
|
||||
what.append(keysL, agentsL, libL, useL, siL, siSay);
|
||||
what.append(keysL, agentsL, libL, memL, useL, siL, siSay);
|
||||
const davFields = [...field(t("Address"), url, t("A folder named magpie is made in it.")),
|
||||
...field(t("User"), user),
|
||||
...field(t("Password"), pass)];
|
||||
@@ -99,7 +100,7 @@ window.davForm = function (v) {
|
||||
? { url: "s3://" + b + (p ? "/" + p : ""), user: keyID.value.trim(), password: secret.value, endpoint: endpoint.value.trim(), region: region.value.trim(), pathStyle: pathStyle.checked }
|
||||
: { url: url.value.trim(), user: user.value.trim(), password: pass.value };
|
||||
try {
|
||||
const r = await api("davsync/save", { ...where, passphrase: phrase.value, keys: keys.checked, agents: agents.checked, library: lib.checked, ...(use.checked || v.usage ? { usage: use.checked } : {}), ...(si.checked || v.signIns ? { signIns: si.checked } : {}) });
|
||||
const r = await api("davsync/save", { ...where, passphrase: phrase.value, keys: keys.checked, agents: agents.checked, library: lib.checked, memory: mem.checked, ...(use.checked || v.usage ? { usage: use.checked } : {}), ...(si.checked || v.signIns ? { signIns: si.checked } : {}) });
|
||||
if (!r.error) syncOpen = "";
|
||||
renderSync(r);
|
||||
if (r.error) return;
|
||||
@@ -118,10 +119,11 @@ window.exportForm = function () {
|
||||
const p2 = input("", t("again"), "password");
|
||||
const [keysL, keys] = tick(t("With the providers' API keys"), true);
|
||||
const [libL, lib] = tick(t("With the library: instructions, MCP servers, skills, hooks and subagents"), true);
|
||||
const [memL, mem] = tick(t("With memory: what the agents know"), true);
|
||||
// sign-ins: off unless picked (qianxunji, curtinp118 on Discord)
|
||||
const [siL, si] = tick(t("With the sign-ins: subscription accounts and plugin sign-ins"), false);
|
||||
const what = el("div", "stack");
|
||||
what.append(keysL, libL, siL);
|
||||
what.append(keysL, libL, memL, siL);
|
||||
const passF = field(t("Passphrase"), p1, t("Needed to open the file. Subscriptions aren't in it: sign in to them on the other computer."));
|
||||
const passSay = passF[1].querySelector(".hint");
|
||||
si.onchange = () => {
|
||||
@@ -138,7 +140,7 @@ window.exportForm = function () {
|
||||
if (p1.value !== p2.value) return say(t("The two passphrases differ"));
|
||||
go.classList.add("busy");
|
||||
try {
|
||||
const r = await api("backup/export", { pass: p1.value, keys: keys.checked, library: lib.checked, signIns: si.checked });
|
||||
const r = await api("backup/export", { pass: p1.value, keys: keys.checked, library: lib.checked, memory: mem.checked, signIns: si.checked });
|
||||
ed.replaceChildren(el("div", "done", t("Saved to {path}", { path: r.path })));
|
||||
} catch (e) {
|
||||
go.classList.remove("busy");
|
||||
@@ -181,9 +183,10 @@ window.importForm = function () {
|
||||
const pass = input("", t("passphrase"), "password");
|
||||
const [agentsL, agents] = tick(t("Set the agents' models too"), true);
|
||||
const [libL, lib] = tick(t("Bring in the library too: instructions, MCP servers, skills, hooks and subagents"), true);
|
||||
const [memL, mem] = tick(t("Bring in memory too, merged with the memories here"), true);
|
||||
const [siL, si] = tick(t("Bring in the sign-ins too, when the file has them"), true);
|
||||
const what = el("div", "stack");
|
||||
what.append(agentsL, libL, siL);
|
||||
what.append(agentsL, libL, memL, siL);
|
||||
ed.append(...field(t("File"), pf), ...field(t("Passphrase"), pass), ...field("", what, t("Providers with the same id are replaced; one that came without a key keeps the key it has here. The library replaces the one here, which is kept with its backups.")));
|
||||
const go = el("button", "text primary", t("Import"));
|
||||
const cancel = el("button", "text", t("Cancel"));
|
||||
@@ -193,7 +196,7 @@ window.importForm = function () {
|
||||
if (!data) return say(t("Choose a file first"));
|
||||
go.classList.add("busy");
|
||||
try {
|
||||
const r = await api("backup/import", { data, pass: pass.value, agents: agents.checked, library: lib.checked, signIns: si.checked });
|
||||
const r = await api("backup/import", { data, pass: pass.value, agents: agents.checked, library: lib.checked, memory: mem.checked, signIns: si.checked });
|
||||
const lines = [t("Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed", { added: r.Added, replaced: r.Replaced, profiles: r.Profiles, agents: r.Agents })];
|
||||
if (r.NeedKey?.length) lines.push(t("Needs a key: {names}", { names: r.NeedKey.join(", ") }));
|
||||
if (r.SignIns) lines.push(...signInsSaid(r.SignIns));
|
||||
|
||||
@@ -27,6 +27,7 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
|
||||
Pass string
|
||||
Keys bool
|
||||
Library *bool // nil is yes
|
||||
Memory *bool // nil is yes
|
||||
SignIns bool // the subscriptions' and plugins' sign-ins too
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
@@ -41,6 +42,9 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
|
||||
if in.Library != nil && !*in.Library {
|
||||
b.Library = nil
|
||||
}
|
||||
if in.Memory != nil && !*in.Memory {
|
||||
b.Memory = nil
|
||||
}
|
||||
if in.SignIns {
|
||||
if err := backup.WithSignIns(&b); err != nil {
|
||||
fail(rw, fmt.Errorf("the sign-ins couldn't be read, so no backup was made: %w", err))
|
||||
@@ -74,6 +78,7 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
|
||||
Pass string
|
||||
Agents bool
|
||||
Library *bool // nil is yes
|
||||
Memory *bool // nil is yes: merged with the memories here
|
||||
SignIns *bool // nil is yes: the backup's sign-ins, when it has them
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
@@ -93,6 +98,7 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
|
||||
parts := backup.All
|
||||
parts.Agents = in.Agents
|
||||
parts.Library = in.Library == nil || *in.Library
|
||||
parts.Memory = in.Memory == nil || *in.Memory
|
||||
parts.SignIns = in.SignIns == nil || *in.SignIns
|
||||
res, err := backup.Restore(b, parts)
|
||||
if err != nil {
|
||||
|
||||
+55
-1
@@ -17,6 +17,9 @@ type memoryView struct {
|
||||
Projects map[string]*memory.Project `json:"projects"`
|
||||
Digest bool `json:"digest"`
|
||||
Agents []string `json:"agents"` // ticked for instructions
|
||||
// Suggestions are memories to make global, and procedures to make
|
||||
// skills (memory.Suggest)
|
||||
Suggestions []memory.Suggestion `json:"suggestions"`
|
||||
}
|
||||
|
||||
func readMemory() (*memoryView, error) {
|
||||
@@ -34,7 +37,14 @@ func readMemory() (*memoryView, error) {
|
||||
if ps == nil {
|
||||
ps = map[string]*memory.Project{}
|
||||
}
|
||||
return &memoryView{Memories: ms, Projects: ps, Digest: on, Agents: agents}, nil
|
||||
sg, err := memory.Suggest()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if sg == nil {
|
||||
sg = []memory.Suggestion{}
|
||||
}
|
||||
return &memoryView{Memories: ms, Projects: ps, Digest: on, Agents: agents, Suggestions: sg}, nil
|
||||
}
|
||||
|
||||
// memoryChanged publishes the user's change to the agents' instructions
|
||||
@@ -127,6 +137,50 @@ func memoryRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
memoryChanged(rw)
|
||||
})
|
||||
// a suggestion taken: memories learned in several projects made one
|
||||
// that holds everywhere, or a procedure made a skill of the library's
|
||||
mux.HandleFunc("POST /api/memory/promote", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
IDs []string `json:"ids"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if _, err := memory.Promote(in.IDs); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
memoryChanged(rw)
|
||||
})
|
||||
mux.HandleFunc("POST /api/memory/skill", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if _, _, err := library.MemorySkill(in.ID); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
memoryChanged(rw)
|
||||
})
|
||||
mux.HandleFunc("POST /api/memory/decline", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if err := memory.Decline(in.Key); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
memoryChanged(rw)
|
||||
})
|
||||
mux.HandleFunc("POST /api/memory/digest", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
On bool `json:"on"`
|
||||
|
||||
@@ -103,7 +103,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await box(L.phrase).fill("correct horse");
|
||||
await toEnd();
|
||||
await form.locator(".bar .primary").click();
|
||||
assert.deepEqual(posts, [{ url: "github://alice/private/magpie-sync", branch: "", password: "fixture-token", passphrase: "correct horse", keys: true, agents: true, library: true }]);
|
||||
assert.deepEqual(posts, [{ url: "github://alice/private/magpie-sync", branch: "", password: "fixture-token", passphrase: "correct horse", keys: true, agents: true, library: true, memory: true }]);
|
||||
await page.waitForFunction((name) => document.querySelector("#syncList .row.pref .name")?.textContent === name, tr("GitHub sync"));
|
||||
assert.equal(await first.locator(".name").textContent(), tr("GitHub sync"));
|
||||
await toStart();
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// What memory suggests, over the Library's Memory list (memory.Suggest):
|
||||
// a memory learned in two projects, named by the projects, made to hold
|
||||
// everywhere; a procedure searched for often made a skill, which the
|
||||
// library then has; and one turned down. Shown only on the In use list
|
||||
// unsearched. Every language, wide and narrow, Chromium and WebKit; no
|
||||
// backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const HOME = "/Users/mem";
|
||||
const at = (d) => `2026-11-0${d}T10:00:00Z`;
|
||||
function library() {
|
||||
return {
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [{ id: "codex", name: "Codex", icon: "", instructions: `${HOME}/.codex/AGENTS.md`, skills: `${HOME}/.codex/skills` }],
|
||||
instructions: { shared: "", sets: [{ id: "default", name: "", active: true, text: "" }], agents: ["codex"] },
|
||||
foundServers: [], projects: [], foundSkills: [], skills: [], servers: [],
|
||||
};
|
||||
}
|
||||
function memories() {
|
||||
return {
|
||||
memories: [
|
||||
{ id: "m1", text: "Use pnpm, not npm", kind: "preference", scope: "project:a", origin: "inferred", status: "active", created: at(1), updated: at(2) },
|
||||
{ id: "m2", text: "use pnpm, not npm", kind: "preference", scope: "project:b", origin: "inferred", status: "active", created: at(1), updated: at(1) },
|
||||
{ id: "m3", text: "To release: tag, wait for the assets, then post", kind: "procedure", scope: "global", origin: "inferred", status: "active", uses: 7, created: at(1), updated: at(3) },
|
||||
{ id: "m4", text: "Dates are ISO 8601", kind: "rule", scope: "project:a", origin: "inferred", status: "active", created: at(1), updated: at(1) },
|
||||
{ id: "m5", text: "Dates are ISO 8601", kind: "rule", scope: "project:b", origin: "inferred", status: "active", created: at(1), updated: at(1) },
|
||||
],
|
||||
projects: { a: { key: "a", name: "magpie", roots: [`${HOME}/magpie`] }, b: { key: "b", name: "site", roots: [`${HOME}/site`] } },
|
||||
digest: true, agents: ["codex"],
|
||||
suggestions: [
|
||||
{ key: "global:m1,m2", to: "global", ids: ["m1", "m2"], text: "Use pnpm, not npm", projects: ["a", "b"] },
|
||||
{ key: "global:m4,m5", to: "global", ids: ["m4", "m5"], text: "Dates are ISO 8601", projects: ["a", "b"] },
|
||||
{ key: "skill:m3", to: "skill", ids: ["m3"], text: "To release: tag, wait for the assets, then post", uses: 7 },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function server(lang, state, lib, sent) {
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const post = route.request().method() === "POST";
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
|
||||
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
|
||||
if (url.pathname === "/api/library") return route.fulfill({ json: lib });
|
||||
if (url.pathname.startsWith("/api/memory/distill") || url.pathname.startsWith("/api/memory/dream")) return route.fulfill({ json: { on: false, models: [], ranges: [7], efforts: [] } });
|
||||
if (url.pathname === "/api/memory/semantic") return route.fulfill({ json: { on: false } });
|
||||
if (url.pathname === "/api/memory/rank") return route.fulfill({ json: { ids: null } });
|
||||
if (url.pathname.startsWith("/api/memory")) {
|
||||
if (post) {
|
||||
const body = route.request().postDataJSON();
|
||||
sent.push({ path: url.pathname, body });
|
||||
const drop = (key) => { state.suggestions = state.suggestions.filter((s) => s.key !== key); };
|
||||
if (url.pathname === "/api/memory/promote") {
|
||||
const kept = state.memories.find((m) => m.id === body.ids[0]);
|
||||
kept.scope = "global";
|
||||
for (const id of body.ids.slice(1)) state.memories.find((m) => m.id === id).status = "superseded";
|
||||
drop("global:" + body.ids.join(","));
|
||||
} else if (url.pathname === "/api/memory/skill") {
|
||||
Object.assign(state.memories.find((m) => m.id === body.id), { status: "archived", skill: "to-release-tag-wait-for" });
|
||||
lib.skills.push({ name: "to-release-tag-wait-for", agents: ["codex"] });
|
||||
drop("skill:" + body.id);
|
||||
} else if (url.pathname === "/api/memory/decline") drop(body.key);
|
||||
}
|
||||
return route.fulfill({ json: state });
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
|
||||
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
|
||||
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
|
||||
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const view = "#view-library";
|
||||
const words = {
|
||||
en: { learned: "Learned in", everywhere: "Use everywhere", skill: "Make a skill", searched: /Searched 7 times/, later: "Not now" },
|
||||
zh: { learned: "在 magpie, site 中学到", everywhere: "在所有项目中使用", skill: "做成 Skill", searched: /被搜索 7 次/, later: "暂不" },
|
||||
"zh-TW": { learned: "magpie, site", everywhere: null, skill: null, searched: /7/, later: "暫不" },
|
||||
ja: { learned: "magpie, site", everywhere: null, skill: null, searched: /7/, later: "後で" },
|
||||
de: { learned: "magpie, site", everywhere: null, skill: null, searched: /7/, later: null },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": memory's suggestions are taken or turned down", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const errors = [];
|
||||
t.after(async () => {
|
||||
if (errors.length) console.log(errors);
|
||||
await browser.close();
|
||||
});
|
||||
for (const lang of Object.keys(words)) for (const width of [980, 420]) {
|
||||
await t.test(`${lang} ${width}`, async () => {
|
||||
const w = words[lang];
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 860 }, reducedMotion: "reduce" });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "memory"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const sent = [];
|
||||
const state = memories();
|
||||
const lib = library();
|
||||
let libGets = 0;
|
||||
await page.route("**/*", server(lang, state, lib, sent));
|
||||
page.on("request", (r) => { if (new URL(r.url()).pathname === "/api/library") libGets++; });
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const sugg = page.locator(`${view} .lib-memsugg [data-sugg]`);
|
||||
await sugg.first().waitFor();
|
||||
assert.equal(await sugg.count(), 3);
|
||||
// above the list, named by the projects it was learned in, in the reader's language
|
||||
const pnpm = page.locator(`${view} [data-sugg="global:m1,m2"]`);
|
||||
assert.ok(lang === "en" ? (await pnpm.locator(".sub").textContent()).includes("Learned in magpie, site") : (await pnpm.locator(".sub").textContent()).includes(w.learned));
|
||||
if (lang !== "en") assert.doesNotMatch(await pnpm.locator(".sub").textContent(), /Learned in/);
|
||||
const rel = page.locator(`${view} [data-sugg="skill:m3"]`);
|
||||
assert.match(await rel.locator(".sub").textContent(), w.searched);
|
||||
if (w.everywhere) assert.equal((await pnpm.locator("button").first().textContent()).trim(), w.everywhere);
|
||||
if (w.skill) assert.equal((await rel.locator("button").first().textContent()).trim(), w.skill);
|
||||
if (w.later) assert.equal((await pnpm.locator("button").last().textContent()).trim(), w.later);
|
||||
const listBox = await page.locator(`${view} .lib-mems`).boundingBox();
|
||||
assert.ok((await page.locator(`${view} .lib-memsugg`).boundingBox()).y < listBox.y, "suggestions not over the list");
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), "the page scrolls sideways");
|
||||
const body = await page.locator(`${view} .lib-body`).boundingBox();
|
||||
for (const b of await page.locator(`${view} .lib-memsugg button`).all()) {
|
||||
const r = await b.boundingBox();
|
||||
assert.ok(r.x + r.width <= body.x + body.width + 1, "a suggestion's button is cut off");
|
||||
}
|
||||
|
||||
// taken: held everywhere, the other superseded, the suggestion gone
|
||||
await pnpm.locator("button").first().click();
|
||||
await pnpm.waitFor({ state: "detached" });
|
||||
assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/promote").body, { ids: ["m1", "m2"] });
|
||||
assert.equal(await page.locator(`${view} .lib-mems .lib-mem`, { hasText: /use pnpm, not npm/ }).count(), 0, "the superseded one still listed");
|
||||
|
||||
// made a skill: the library is read again, and it has it
|
||||
const before = libGets;
|
||||
await rel.locator("button").first().click();
|
||||
await rel.waitFor({ state: "detached" });
|
||||
assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/skill").body, { id: "m3" });
|
||||
for (let i = 0; i < 50 && libGets <= before; i++) await page.waitForTimeout(50);
|
||||
assert.ok(libGets > before, "the library wasn't read again");
|
||||
|
||||
// turned down
|
||||
const iso = page.locator(`${view} [data-sugg="global:m4,m5"]`);
|
||||
await iso.locator("button").last().click();
|
||||
await page.locator(`${view} .lib-memsugg`).waitFor({ state: "detached" });
|
||||
assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/decline").body, { key: "global:m4,m5" });
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// not over a search, another list, or a project's memories
|
||||
test(engine + ": suggestions show on the In use list only", async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const ctx = await browser.newContext({ viewport: { width: 980, height: 860 }, reducedMotion: "reduce" });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "memory"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
await page.route("**/*", server("en", memories(), library(), []));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
await page.locator(`${view} .lib-memsugg`).waitFor();
|
||||
await page.locator(`${view} .lib-memstatus .opt`, { hasText: "Archived" }).click();
|
||||
await page.locator(`${view} .lib-memsugg`).waitFor({ state: "detached" });
|
||||
await page.locator(`${view} .lib-memstatus .opt`).first().click();
|
||||
await page.locator(`${view} .lib-memsugg`).waitFor();
|
||||
await page.locator(`${view} .lib-memq`).first().fill("pnpm");
|
||||
await page.locator(`${view} .lib-memsugg`).waitFor({ state: "detached" });
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
@@ -143,7 +143,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await save.click();
|
||||
await form.waitFor({ state: "detached" });
|
||||
assert.deepEqual(posts, [{ url: "s3://magpie-sync/team", user: "AKIDEXAMPLE", password: "s3cr3t", endpoint: "https://acct.r2.cloudflarestorage.com",
|
||||
region: "auto", pathStyle: true, passphrase: "correct horse", keys: true, agents: true, library: true }]);
|
||||
region: "auto", pathStyle: true, passphrase: "correct horse", keys: true, agents: true, library: true, memory: true }]);
|
||||
|
||||
assert.equal(await first.locator(".name").textContent(), zh ? "S3 同步" : "S3 sync");
|
||||
assert.equal(await first.locator(".sub").textContent(), (zh ? "尚未同步 · " : "Not synced yet · ") + "s3://magpie-sync/team · acct.r2.cloudflarestorage.com");
|
||||
|
||||
@@ -137,7 +137,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
|
||||
await save.click();
|
||||
await form.waitFor({ state: "detached" });
|
||||
assert.deepEqual(posts, [{ url: DAV.url, user: "me", password: "", passphrase: "", keys: true, agents: true, library: true }]);
|
||||
assert.deepEqual(posts, [{ url: DAV.url, user: "me", password: "", passphrase: "", keys: true, agents: true, library: true, memory: true }]);
|
||||
assert.equal(await first.locator(".name").textContent(), w.davRow);
|
||||
assert.ok((await first.locator(".sub").textContent()).endsWith(" · " + w.s3Kept), "the row says S3's settings are kept");
|
||||
assert.deepEqual(errors, []);
|
||||
|
||||
@@ -164,7 +164,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await p2.fill("correct horse");
|
||||
await noneWider(page);
|
||||
await click(form.locator("button.primary"));
|
||||
assert.deepEqual(await waitPost("/api/backup/export"), { pass: "correct horse", keys: true, library: true, signIns: true });
|
||||
assert.deepEqual(await waitPost("/api/backup/export"), { pass: "correct horse", keys: true, library: true, signIns: true, memory: true });
|
||||
await form.locator(".done").waitFor();
|
||||
await click(exportRow.locator("button"));
|
||||
|
||||
|
||||
@@ -93,8 +93,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
// off, nothing changed by anything: the description of the whole lot
|
||||
assert.equal(await first.locator(".name").textContent(), zh ? "WebDAV / S3 / GitHub 同步" : "WebDAV, S3 or GitHub sync");
|
||||
assert.equal(await first.locator(".sub").textContent(), zh
|
||||
? "让每台电脑上的供应商(含 API Key)、设置、Profile、agent 的模型、资源库保持一致"
|
||||
: "Keeps providers with their API keys, settings, profiles, agents' models, library the same on every computer");
|
||||
? "让每台电脑上的供应商(含 API Key)、设置、Profile、agent 的模型、资源库、记忆保持一致"
|
||||
: "Keeps providers with their API keys, settings, profiles, agents' models, library, memory the same on every computer");
|
||||
|
||||
// an open form is someone typing: a focus while one is open must not
|
||||
// rebuild it under them (#104)
|
||||
@@ -126,7 +126,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await form.waitFor({ state: "visible" });
|
||||
const tick = (word) => form.locator("label.tick", { hasText: word }).locator("input");
|
||||
assert.equal(await tick("API Key").isChecked(), true);
|
||||
assert.equal(await tick(zh ? "agent" : "Agents' models").isChecked(), false, "agents' models must be unticked, as the CLI left it");
|
||||
assert.equal(await tick(zh ? "各 agent 选的模型" : "Agents' models").isChecked(), false, "agents' models must be unticked, as the CLI left it");
|
||||
assert.equal(await tick(zh ? "资源库" : "Library").isChecked(), false, "the library must be unticked, as the CLI left it");
|
||||
await first.locator(".val button", { hasText: zh ? "关闭" : "Close" }).click();
|
||||
await form.waitFor({ state: "detached" });
|
||||
@@ -139,9 +139,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
"an S3 setup changed behind the window must reach the page too");
|
||||
assert.equal(await first.locator(".name").textContent(), zh ? "S3 同步" : "S3 sync");
|
||||
|
||||
// off again, keys and agents out: the description names what is on,
|
||||
// off again, keys, agents and memory out: the description names what is on,
|
||||
// as the CLI's list does
|
||||
sync.value = { on: false, keys: false, agents: false, library: true };
|
||||
sync.value = { on: false, keys: false, agents: false, library: true, memory: false };
|
||||
await focus();
|
||||
assert.equal(await settle(async () => (await first.locator(".sub").textContent()) === (zh
|
||||
? "让每台电脑上的供应商(不含 API Key)、设置、Profile、资源库保持一致"
|
||||
@@ -154,8 +154,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
sync.value = { on: false };
|
||||
await focus();
|
||||
assert.equal(await settle(async () => (await first.locator(".sub").textContent()) === (zh
|
||||
? "让每台电脑上的供应商(含 API Key)、设置、Profile、agent 的模型、资源库保持一致"
|
||||
: "Keeps providers with their API keys, settings, profiles, agents' models, library the same on every computer")), true,
|
||||
? "让每台电脑上的供应商(含 API Key)、设置、Profile、agent 的模型、资源库、记忆保持一致"
|
||||
: "Keeps providers with their API keys, settings, profiles, agents' models, library, memory the same on every computer")), true,
|
||||
"a view with no toggles must read as the defaults");
|
||||
|
||||
assert.deepEqual(errors, []);
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
)
|
||||
|
||||
// MemorySkill makes the procedure memory with id a skill of the library's
|
||||
// own, as Memory's suggestion does once the agents search for it often:
|
||||
// a SKILL.md holding its text (and why), named from its words, given to
|
||||
// the agents ticked for instructions (the ones memory is published to),
|
||||
// or to every agent with skills when none is. The memory is archived
|
||||
// then, noted as that skill's (memory.MadeSkill). It answers with the
|
||||
// skill's name.
|
||||
func MemorySkill(id string) (*Result, string, error) {
|
||||
m, err := memory.Get(id)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if m.Kind != memory.Procedure {
|
||||
return nil, "", errors.New("only a procedure is made a skill")
|
||||
}
|
||||
if m.Skill != "" {
|
||||
return nil, "", fmt.Errorf("it is the skill %s already", m.Skill)
|
||||
}
|
||||
var name string
|
||||
res, err := change(func(l *Library) error {
|
||||
name = freeOwnName(l, skillNameOf(m))
|
||||
dir := skillDir(name)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(skillText(name, m)), 0o644); err != nil {
|
||||
os.RemoveAll(dir)
|
||||
return err
|
||||
}
|
||||
l.Skills = append(l.Skills, &Skill{Name: name, Agents: skillAgentsOf(l)})
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if err := memory.MadeSkill(id, name); err != nil {
|
||||
return res, name, fmt.Errorf("the skill %s is made, but the memory couldn't be set aside: %w", name, err)
|
||||
}
|
||||
return res, name, nil
|
||||
}
|
||||
|
||||
// skillAgentsOf is who a skill made from memory goes to.
|
||||
func skillAgentsOf(l *Library) []string {
|
||||
var ticked, all []string
|
||||
for _, t := range Targets() {
|
||||
if t.Skills == "" {
|
||||
continue
|
||||
}
|
||||
all = append(all, t.Agent.ID)
|
||||
for _, a := range l.Instructions.Agents {
|
||||
if a == t.Agent.ID {
|
||||
ticked = append(ticked, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(ticked) > 0 {
|
||||
return ticked
|
||||
}
|
||||
if all == nil {
|
||||
all = []string{}
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
// skillNameOf is a skill's name from a memory's first words in Latin
|
||||
// letters, or from its id when it has fewer than two (a memory in Chinese).
|
||||
func skillNameOf(m *memory.Memory) string {
|
||||
var words []string
|
||||
for _, w := range strings.FieldsFunc(strings.ToLower(m.Text), func(r rune) bool {
|
||||
return r > unicode.MaxASCII || !unicode.IsLetter(r) && !unicode.IsDigit(r)
|
||||
}) {
|
||||
if len(words) == 5 {
|
||||
break
|
||||
}
|
||||
words = append(words, w)
|
||||
}
|
||||
name := strings.Join(words, "-")
|
||||
if len(name) > 40 {
|
||||
name = strings.TrimRight(name[:40], "-")
|
||||
}
|
||||
if len(words) < 2 || checkName("skill", name) != nil { // one word in a Chinese text names nothing
|
||||
name = "procedure-" + strings.TrimPrefix(m.ID, "m_")
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// freeOwnName is name, or name-2, -3… when the library or its folder has
|
||||
// one by that name already.
|
||||
func freeOwnName(l *Library, name string) string {
|
||||
for i := 1; ; i++ {
|
||||
n := name
|
||||
if i > 1 {
|
||||
n = fmt.Sprintf("%s-%d", name, i)
|
||||
}
|
||||
if l.skill(n) != nil {
|
||||
continue
|
||||
}
|
||||
if _, err := os.Lstat(skillDir(n)); err == nil {
|
||||
continue
|
||||
}
|
||||
return n
|
||||
}
|
||||
}
|
||||
|
||||
// skillText is the SKILL.md of a skill made from m: its first line says
|
||||
// when to use it, as a description does, and the rest is the procedure.
|
||||
func skillText(name string, m *memory.Memory) string {
|
||||
desc, _, _ := strings.Cut(strings.TrimSpace(m.Text), "\n")
|
||||
if r := []rune(desc); len(r) > 200 {
|
||||
desc = string(r[:200]) + "…"
|
||||
}
|
||||
q, _ := json.Marshal(desc) // a JSON string is a YAML one
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "---\nname: %s\ndescription: %s\n---\n\n", name, q)
|
||||
b.WriteString(strings.TrimSpace(m.Text))
|
||||
b.WriteString("\n")
|
||||
if m.Why != "" {
|
||||
b.WriteString("\nWhy: " + strings.TrimSpace(m.Why) + "\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/memory"
|
||||
)
|
||||
|
||||
// A procedure made a skill: a SKILL.md of its own in the library, named
|
||||
// from its words, given to the agents ticked for instructions, and the
|
||||
// memory set aside as that skill's. A second by the same words gets
|
||||
// another name, and one in Chinese one from its id.
|
||||
func TestMemorySkill(t *testing.T) {
|
||||
sandbox(t)
|
||||
ok(t)(SaveInstructions(InstructionsChange{Agents: []string{"codex"}}))
|
||||
mk := func(text string) *memory.Memory {
|
||||
t.Helper()
|
||||
k, s, why := memory.Procedure, memory.Global, "assets come last"
|
||||
m, _, err := memory.Save(memory.Input{Text: &text, Kind: &k, Scope: &s, Why: &why}, memory.FromAgent, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
m := mk("To release: tag it, wait for the 16 assets, then post.\nNever before.")
|
||||
_, name, err := MemorySkill(m.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if name != "to-release-tag-it-wait" {
|
||||
t.Fatalf("named %q", name)
|
||||
}
|
||||
md := read(t, filepath.Join(skillDir(name), "SKILL.md"))
|
||||
for _, w := range []string{"name: to-release-tag-it-wait\n", `description: "To release: tag it, wait for the 16 assets, then post."`, "Never before.", "Why: assets come last"} {
|
||||
if !strings.Contains(md, w) {
|
||||
t.Fatalf("SKILL.md lacks %q:\n%s", w, md)
|
||||
}
|
||||
}
|
||||
l, err := load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := l.skill(name)
|
||||
if s == nil || s.Source != nil || !slices.Equal(s.Agents, []string{"codex"}) {
|
||||
t.Fatalf("in the library: %+v", s)
|
||||
}
|
||||
if got, _ := memory.Get(m.ID); got.Status != memory.Archived || got.Skill != name {
|
||||
t.Fatalf("the memory after: %+v", got)
|
||||
}
|
||||
if _, _, err := MemorySkill(m.ID); err == nil {
|
||||
t.Fatal("made a skill twice")
|
||||
}
|
||||
_, name2, err := MemorySkill(mk("To release: tag it, wait for CI first.").ID)
|
||||
if err != nil || name2 != "to-release-tag-it-wait-2" {
|
||||
t.Fatalf("second: %q, %v", name2, err)
|
||||
}
|
||||
_, name3, err := MemorySkill(mk("发布:先打 tag,等资产齐了再发帖。").ID)
|
||||
if err != nil || !strings.HasPrefix(name3, "procedure-") {
|
||||
t.Fatalf("Chinese: %q, %v", name3, err)
|
||||
}
|
||||
// only a procedure
|
||||
k, sc, text := memory.Rule, memory.Global, "Never force-push."
|
||||
r, _, _ := memory.Save(memory.Input{Text: &text, Kind: &k, Scope: &sc}, memory.FromAgent, nil, nil)
|
||||
if _, _, err := MemorySkill(r.ID); err == nil {
|
||||
t.Fatal("a rule was made a skill")
|
||||
}
|
||||
}
|
||||
@@ -88,9 +88,16 @@ type Memory struct {
|
||||
Sources []Source `json:"sources,omitempty"`
|
||||
Created time.Time `json:"created"`
|
||||
Updated time.Time `json:"updated"`
|
||||
// Edited is when the user last changed it (Edit by the user, Save
|
||||
// of what they typed): a change made then is theirs, which a sync
|
||||
// from another computer tells apart from an agent's or a tidy's
|
||||
// (Combine)
|
||||
Edited time.Time `json:"edited,omitzero"`
|
||||
// Used is when a search last returned it, Uses how many times
|
||||
Used time.Time `json:"used,omitzero"`
|
||||
Uses int `json:"uses,omitempty"`
|
||||
// Skill is the Library skill this procedure was made (MadeSkill)
|
||||
Skill string `json:"skill,omitempty"`
|
||||
}
|
||||
|
||||
// Source is where a memory was said or found.
|
||||
@@ -126,6 +133,13 @@ type file struct {
|
||||
// conversations that the user deleted or archived, the last
|
||||
// maxDismissed: never proposed again
|
||||
Dismissed []string `json:"dismissed,omitempty"`
|
||||
// Removed is when each memory deleted for good was deleted, kept
|
||||
// keepRemoved: a sync doesn't bring it back from a computer that
|
||||
// still has it (Combine)
|
||||
Removed map[string]time.Time `json:"removed,omitempty"`
|
||||
// Declined are the suggestions the user turned down (Suggest), by
|
||||
// key, the last maxDeclined
|
||||
Declined []string `json:"declined,omitempty"`
|
||||
}
|
||||
|
||||
// maxDismissed is how many dismissed texts are kept.
|
||||
@@ -357,6 +371,9 @@ func norm(s string) string {
|
||||
func Save(in Input, origin string, src *Source, proj *Project) (m *Memory, added bool, err error) {
|
||||
t := now().UTC()
|
||||
m = &Memory{Kind: Fact, Scope: Global, Origin: origin, Status: Active, Created: t, Updated: t}
|
||||
if origin == FromUser {
|
||||
m.Edited = t
|
||||
}
|
||||
apply(m, in)
|
||||
if err := check(m); err != nil {
|
||||
return nil, false, err
|
||||
@@ -405,6 +422,9 @@ func Save(in Input, origin string, src *Source, proj *Project) (m *Memory, added
|
||||
}
|
||||
o.Sources = keepSources(append(o.Sources, m.Sources...))
|
||||
o.Updated = t
|
||||
if origin == FromUser {
|
||||
o.Edited = t
|
||||
}
|
||||
m = o
|
||||
return nil
|
||||
}
|
||||
@@ -493,6 +513,9 @@ func editIn(f *file, m *Memory, in Input, byUser bool) error {
|
||||
c.Origin = FromUser
|
||||
}
|
||||
c.Updated = now().UTC()
|
||||
if byUser {
|
||||
c.Edited = c.Updated
|
||||
}
|
||||
*m = c
|
||||
return nil
|
||||
}
|
||||
@@ -538,6 +561,7 @@ func Remove(ids ...string) error {
|
||||
f.Memories = slices.DeleteFunc(f.Memories, func(m *Memory) bool {
|
||||
if slices.Contains(ids, m.ID) {
|
||||
dismiss(f, m)
|
||||
removed(f, m.ID)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// What memory suggests the user make more of (Suggest): a memory learned
|
||||
// in two or more projects is one that holds everywhere, and a procedure
|
||||
// the agents search for often is worth a skill of its own.
|
||||
const (
|
||||
ToGlobal = "global"
|
||||
ToSkill = "skill"
|
||||
)
|
||||
|
||||
// skillUses is how often searches return a procedure before it is
|
||||
// suggested as a skill: often enough that the agents reach for it, not
|
||||
// one day's work.
|
||||
const skillUses = 5
|
||||
|
||||
// alike is how many of two memories' words they share (Jaccard) before
|
||||
// they count as saying the same thing in two projects, when their texts
|
||||
// aren't the same. Short texts must be the same: four words in common of
|
||||
// five is another fact as often as the same one.
|
||||
const (
|
||||
alike = 0.6
|
||||
alikeWords = 6
|
||||
)
|
||||
|
||||
// maxDeclined is how many suggestions turned down are kept.
|
||||
const maxDeclined = 500
|
||||
|
||||
// Suggestion is one thing memory suggests.
|
||||
type Suggestion struct {
|
||||
Key string `json:"key"` // what Decline takes
|
||||
To string `json:"to"` // ToGlobal or ToSkill
|
||||
IDs []string `json:"ids"` // the memories it is about, the one kept first
|
||||
Text string `json:"text"` // the text kept
|
||||
// Projects are the projects' keys a ToGlobal one was learned in
|
||||
Projects []string `json:"projects,omitempty"`
|
||||
Uses int `json:"uses,omitempty"` // a ToSkill one's
|
||||
}
|
||||
|
||||
// Suggest is what memory suggests now, none the user turned down: the
|
||||
// project memories that say the same in two or more projects, or one
|
||||
// whose sources were in two or more, to make global; and the procedures
|
||||
// returned skillUses times or more, not made a skill yet, to make one.
|
||||
func Suggest() ([]Suggestion, error) {
|
||||
f, err := view()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := append(globalSuggestions(f), skillSuggestions(f)...)
|
||||
return slices.DeleteFunc(out, func(s Suggestion) bool { return slices.Contains(f.Declined, s.Key) }), nil
|
||||
}
|
||||
|
||||
func projectOfScope(s string) string {
|
||||
k, ok := strings.CutPrefix(s, "project:")
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
func globalSuggestions(f *file) []Suggestion {
|
||||
var pool []*Memory
|
||||
for _, m := range f.Memories {
|
||||
if m.Status == Active && projectOfScope(m.Scope) != "" {
|
||||
pool = append(pool, m)
|
||||
}
|
||||
}
|
||||
words := make([][]string, len(pool))
|
||||
for i, m := range pool {
|
||||
w := Words(m.Text)
|
||||
slices.Sort(w)
|
||||
words[i] = slices.Compact(w)
|
||||
}
|
||||
// memories that say the same in different projects, joined
|
||||
up := make([]int, len(pool))
|
||||
for i := range up {
|
||||
up[i] = i
|
||||
}
|
||||
var root func(int) int
|
||||
root = func(i int) int {
|
||||
for up[i] != i {
|
||||
up[i] = up[up[i]]
|
||||
i = up[i]
|
||||
}
|
||||
return i
|
||||
}
|
||||
for i := range pool {
|
||||
for j := i + 1; j < len(pool); j++ {
|
||||
if pool[i].Scope == pool[j].Scope {
|
||||
continue
|
||||
}
|
||||
if norm(pool[i].Text) == norm(pool[j].Text) || sameWords(words[i], words[j]) {
|
||||
up[root(j)] = root(i)
|
||||
}
|
||||
}
|
||||
}
|
||||
groups := map[int][]*Memory{}
|
||||
for i, m := range pool {
|
||||
groups[root(i)] = append(groups[root(i)], m)
|
||||
}
|
||||
var out []Suggestion
|
||||
for _, ms := range groups {
|
||||
ps := map[string]bool{}
|
||||
for _, m := range ms {
|
||||
ps[projectOfScope(m.Scope)] = true
|
||||
for _, s := range m.Sources {
|
||||
if k := projectAt(f, s.Dir); k != "" {
|
||||
ps[k] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(ps) < 2 {
|
||||
continue
|
||||
}
|
||||
slices.SortFunc(ms, keptFirst)
|
||||
s := Suggestion{To: ToGlobal, Text: ms[0].Text}
|
||||
for _, m := range ms {
|
||||
s.IDs = append(s.IDs, m.ID)
|
||||
}
|
||||
for k := range ps {
|
||||
s.Projects = append(s.Projects, k)
|
||||
}
|
||||
slices.Sort(s.Projects)
|
||||
s.Key = ToGlobal + ":" + strings.Join(slices.Sorted(slices.Values(s.IDs)), ",")
|
||||
out = append(out, s)
|
||||
}
|
||||
slices.SortFunc(out, func(a, b Suggestion) int { return strings.Compare(a.Key, b.Key) })
|
||||
return out
|
||||
}
|
||||
|
||||
// sameWords is whether two sorted word sets share alike of their words,
|
||||
// both long enough to tell.
|
||||
func sameWords(a, b []string) bool {
|
||||
if len(a) < alikeWords || len(b) < alikeWords {
|
||||
return false
|
||||
}
|
||||
n := 0
|
||||
for i, j := 0, 0; i < len(a) && j < len(b); {
|
||||
switch {
|
||||
case a[i] == b[j]:
|
||||
n++
|
||||
i++
|
||||
j++
|
||||
case a[i] < b[j]:
|
||||
i++
|
||||
default:
|
||||
j++
|
||||
}
|
||||
}
|
||||
return float64(n) >= alike*float64(len(a)+len(b)-n)
|
||||
}
|
||||
|
||||
// projectAt is the key of the project whose folder dir is in, or "".
|
||||
func projectAt(f *file, dir string) string {
|
||||
if dir == "" {
|
||||
return ""
|
||||
}
|
||||
dir = filepath.Clean(dir)
|
||||
best, at := "", 0
|
||||
for k, p := range f.Projects {
|
||||
for _, r := range p.Roots {
|
||||
r = filepath.Clean(r)
|
||||
if (dir == r || strings.HasPrefix(dir, r+string(filepath.Separator))) && len(r) > at {
|
||||
best, at = k, len(r)
|
||||
}
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// keptFirst orders memories saying the same thing by which one stays
|
||||
// when they are made one: the user's own or pinned, then the most used,
|
||||
// then the latest changed.
|
||||
func keptFirst(a, b *Memory) int {
|
||||
if Fixed(a) != Fixed(b) {
|
||||
if Fixed(a) {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if a.Uses != b.Uses {
|
||||
return b.Uses - a.Uses
|
||||
}
|
||||
if c := b.Updated.Compare(a.Updated); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.ID, b.ID)
|
||||
}
|
||||
|
||||
func skillSuggestions(f *file) []Suggestion {
|
||||
var out []Suggestion
|
||||
for _, m := range f.Memories {
|
||||
if m.Status != Active || m.Kind != Procedure || m.Skill != "" || m.Uses < skillUses {
|
||||
continue
|
||||
}
|
||||
out = append(out, Suggestion{Key: ToSkill + ":" + m.ID, To: ToSkill, IDs: []string{m.ID}, Text: m.Text, Uses: m.Uses})
|
||||
}
|
||||
slices.SortFunc(out, func(a, b Suggestion) int { return b.Uses - a.Uses })
|
||||
return out
|
||||
}
|
||||
|
||||
// Decline turns a suggestion down: it isn't made again. A ToGlobal one
|
||||
// that another project's memory joins later is another suggestion.
|
||||
func Decline(key string) error {
|
||||
if key == "" {
|
||||
return errors.New("name the suggestion")
|
||||
}
|
||||
return change(func(f *file) error {
|
||||
if slices.Contains(f.Declined, key) {
|
||||
return errSkip
|
||||
}
|
||||
f.Declined = append(f.Declined, key)
|
||||
if len(f.Declined) > maxDeclined {
|
||||
f.Declined = f.Declined[len(f.Declined)-maxDeclined:]
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ErrNotSuggested is a suggestion taken that is no longer made.
|
||||
var ErrNotSuggested = errors.New("that isn't suggested any more")
|
||||
|
||||
// Promote makes the project memories with ids one global memory, as the
|
||||
// user asked: the one kept first (the user's own or pinned, the most
|
||||
// used, the latest) holds everywhere from now, carrying the others' tags
|
||||
// and sources, and the others are superseded by it. It is the user's
|
||||
// change, so a sync never undoes it with an older one.
|
||||
func Promote(ids []string) (*Memory, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, errors.New("name the memories")
|
||||
}
|
||||
var kept *Memory
|
||||
err := change(func(f *file) error {
|
||||
var ms []*Memory
|
||||
for _, id := range ids {
|
||||
m := find(f, id)
|
||||
if m == nil || m.Status != Active || projectOfScope(m.Scope) == "" {
|
||||
return ErrNotSuggested
|
||||
}
|
||||
ms = append(ms, m)
|
||||
}
|
||||
slices.SortFunc(ms, keptFirst)
|
||||
t := now().UTC()
|
||||
// the same text global already: that one is kept, and these go into it
|
||||
for _, g := range f.Memories {
|
||||
if g.Scope == Global && (g.Status == Active || g.Status == Candidate) && norm(g.Text) == norm(ms[0].Text) {
|
||||
g.Status = Active
|
||||
ms = append([]*Memory{g}, ms...)
|
||||
break
|
||||
}
|
||||
}
|
||||
k := ms[0]
|
||||
k.Scope = Global
|
||||
for _, o := range ms[1:] {
|
||||
for _, tg := range o.Tags {
|
||||
if !slices.Contains(k.Tags, tg) {
|
||||
k.Tags = append(k.Tags, tg)
|
||||
}
|
||||
}
|
||||
k.Sources = keepSources(append(k.Sources, o.Sources...))
|
||||
k.Uses += o.Uses
|
||||
if o.Used.After(k.Used) {
|
||||
k.Used = o.Used
|
||||
}
|
||||
k.Pinned = k.Pinned || o.Pinned
|
||||
o.Status, o.SupersededBy, o.Updated, o.Edited = Superseded, k.ID, t, t
|
||||
}
|
||||
k.Updated, k.Edited = t, t
|
||||
kept = k
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := *kept
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// MadeSkill notes that the procedure with id was made the skill called
|
||||
// name: it is archived, since the skill holds it now, and isn't suggested
|
||||
// again. Restored, it is searched again, still noted as that skill's.
|
||||
func MadeSkill(id, name string) error {
|
||||
return change(func(f *file) error {
|
||||
m := find(f, id)
|
||||
if m == nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
t := now().UTC()
|
||||
m.Skill = name
|
||||
m.Status = Archived
|
||||
m.Updated, m.Edited = t, t
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func uses(t *testing.T, id string, n int) {
|
||||
t.Helper()
|
||||
if err := change(func(f *file) error { find(f, id).Uses = n; return nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func suggested(t *testing.T) []Suggestion {
|
||||
t.Helper()
|
||||
s, err := Suggest()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// A memory learned in two projects is suggested to hold everywhere: the
|
||||
// same text, or the same words in another order; one project's memories
|
||||
// alone, or two short ones sharing words, are not.
|
||||
func TestSuggestGlobalAcrossProjects(t *testing.T) {
|
||||
fresh(t)
|
||||
a := save(t, "Commits list explicit filenames, never git add -A.", Rule, "project:a")
|
||||
b := save(t, "commits list explicit filenames never git add -A", Rule, "project:b")
|
||||
c := save(t, "Never git add -A: commits list explicit filenames.", Rule, "project:c")
|
||||
save(t, "Builds run on mote.", Rule, "project:a")
|
||||
save(t, "Builds run on CI.", Rule, "project:b") // short, alike in words: another fact
|
||||
save(t, "Tests run with -race.", Rule, "project:a")
|
||||
save(t, "Tests run with -race.", Rule, "agent:codex")
|
||||
got := suggested(t)
|
||||
if len(got) != 1 || got[0].To != ToGlobal || !slices.Equal(got[0].Projects, []string{"a", "b", "c"}) {
|
||||
t.Fatalf("suggested %+v, want the one rule of three projects", got)
|
||||
}
|
||||
ids := slices.Sorted(slices.Values(got[0].IDs))
|
||||
if want := slices.Sorted(slices.Values([]string{a.ID, b.ID, c.ID})); !slices.Equal(ids, want) {
|
||||
t.Fatalf("ids %v, want %v", ids, want)
|
||||
}
|
||||
}
|
||||
|
||||
// One project's memory whose sources were in another project's folder
|
||||
// was learned in both.
|
||||
func TestSuggestGlobalBySourceFolder(t *testing.T) {
|
||||
fresh(t)
|
||||
NoteProject(&Project{Key: "a", Name: "a", Roots: []string{"/src/a"}})
|
||||
NoteProject(&Project{Key: "b", Name: "b", Roots: []string{"/src/b"}})
|
||||
k, s := Preference, "project:a"
|
||||
text := "Replies are short."
|
||||
Save(Input{Text: &text, Kind: &k, Scope: &s}, FromAgent, &Source{Agent: "codex", Dir: "/src/a"}, nil)
|
||||
if got := suggested(t); len(got) != 0 {
|
||||
t.Fatalf("one project's: %+v", got)
|
||||
}
|
||||
Save(Input{Text: &text, Kind: &k, Scope: &s}, FromAgent, &Source{Agent: "codex", Dir: "/src/b/web"}, nil)
|
||||
if got := suggested(t); len(got) != 1 || !slices.Equal(got[0].Projects, []string{"a", "b"}) {
|
||||
t.Fatalf("suggested %+v, want it from a and b", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Taken, the one kept holds everywhere, carrying the others' sources and
|
||||
// uses, and they are superseded by it; the user's own is the one kept,
|
||||
// as written. It is the user's change, and isn't suggested again.
|
||||
func TestPromoteKeepsTheUsersOwn(t *testing.T) {
|
||||
at := fresh(t)
|
||||
a := save(t, "Use pnpm, not npm.", Preference, "project:a")
|
||||
uses(t, a.ID, 4)
|
||||
text, k, s := "use pnpm, not npm", Preference, "project:b"
|
||||
b, _, _ := Save(Input{Text: &text, Kind: &k, Scope: &s}, FromUser, nil, nil)
|
||||
*at = at.Add(time.Hour)
|
||||
m, err := Promote([]string{a.ID, b.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.ID != b.ID || m.Scope != Global || m.Text != "use pnpm, not npm" || m.Uses != 4 || !byUser(m) {
|
||||
t.Fatalf("kept %+v, want the user's own, global", m)
|
||||
}
|
||||
o, _ := Get(a.ID)
|
||||
if o.Status != Superseded || o.SupersededBy != b.ID {
|
||||
t.Fatalf("the other: %+v", o)
|
||||
}
|
||||
if got := suggested(t); len(got) != 0 {
|
||||
t.Fatalf("suggested again: %+v", got)
|
||||
}
|
||||
// a memory no longer in a project is no promotion
|
||||
if _, err := Promote([]string{a.ID}); err != ErrNotSuggested {
|
||||
t.Fatalf("promoted a superseded one: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The same text global already: the project ones go into it.
|
||||
func TestPromoteIntoTheGlobalOne(t *testing.T) {
|
||||
fresh(t)
|
||||
g := save(t, "Dates are ISO 8601.", Rule, Global)
|
||||
a := save(t, "Dates are ISO 8601.", Rule, "project:a")
|
||||
b := save(t, "Dates are ISO 8601.", Rule, "project:b")
|
||||
m, err := Promote([]string{a.ID, b.ID})
|
||||
if err != nil || m.ID != g.ID || m.Scope != Global {
|
||||
t.Fatalf("kept %+v, %v; want the global one", m, err)
|
||||
}
|
||||
for _, id := range []string{a.ID, b.ID} {
|
||||
if o, _ := Get(id); o.Status != Superseded || o.SupersededBy != g.ID || o.Scope == Global {
|
||||
t.Fatalf("%+v", o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A procedure searched for often is suggested as a skill until it is
|
||||
// one, and a suggestion turned down stays down, on another computer too.
|
||||
func TestSuggestSkillAndDecline(t *testing.T) {
|
||||
a, b, _ := twoComputers(t)
|
||||
a.use(t)
|
||||
p := save(t, "To release: tag, wait for the assets, then post.", Procedure, Global)
|
||||
r := save(t, "Never force-push main.", Rule, Global)
|
||||
uses(t, p.ID, skillUses-1)
|
||||
uses(t, r.ID, 50)
|
||||
if got := suggested(t); len(got) != 0 {
|
||||
t.Fatalf("suggested %+v before it was used enough", got)
|
||||
}
|
||||
uses(t, p.ID, skillUses)
|
||||
got := suggested(t)
|
||||
if len(got) != 1 || got[0].To != ToSkill || got[0].IDs[0] != p.ID || got[0].Uses != skillUses {
|
||||
t.Fatalf("suggested %+v, want the procedure", got)
|
||||
}
|
||||
if err := Decline(got[0].Key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := suggested(t); len(got) != 0 {
|
||||
t.Fatalf("declined, still suggested: %+v", got)
|
||||
}
|
||||
carry(t, a, b)
|
||||
b.use(t)
|
||||
if got := suggested(t); len(got) != 0 {
|
||||
t.Fatalf("declined on a, suggested on b: %+v", got)
|
||||
}
|
||||
// made a skill: archived, noted, not suggested
|
||||
a.use(t)
|
||||
q := save(t, "To deploy the site: wrangler deploy, then curl it.", Procedure, Global)
|
||||
uses(t, q.ID, skillUses)
|
||||
if err := MadeSkill(q.ID, "deploy-site"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m, _ := Get(q.ID); m.Status != Archived || m.Skill != "deploy-site" {
|
||||
t.Fatalf("%+v", m)
|
||||
}
|
||||
if got := suggested(t); len(got) != 0 {
|
||||
t.Fatalf("a skill already, suggested: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"maps"
|
||||
"os"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
// keepRemoved is how long a deletion is remembered: a computer that
|
||||
// syncs again within it doesn't bring the memory back. One away longer
|
||||
// does, as a memory it still holds.
|
||||
const keepRemoved = 180 * 24 * time.Hour
|
||||
|
||||
// removed notes that the memory with id was deleted for good, now.
|
||||
func removed(f *file, id string) {
|
||||
if f.Removed == nil {
|
||||
f.Removed = map[string]time.Time{}
|
||||
}
|
||||
f.Removed[id] = now().UTC()
|
||||
}
|
||||
|
||||
// Bundle is what of memory goes to another computer, in a backup or a
|
||||
// sync: the memories in every state, the projects they are kept for, the
|
||||
// distilled texts the user threw away and the memories deleted. The
|
||||
// published digests and the vectors (memembed) are this computer's own,
|
||||
// made again from the memories here.
|
||||
type Bundle struct {
|
||||
Memories []*Memory `json:"memories"`
|
||||
Projects map[string]*Project `json:"projects,omitempty"`
|
||||
Dismissed []string `json:"dismissed,omitempty"`
|
||||
Removed map[string]time.Time `json:"removed,omitempty"`
|
||||
Declined []string `json:"declined,omitempty"`
|
||||
}
|
||||
|
||||
// Collect is this computer's memory, to carry: nil when memory.json isn't
|
||||
// there, an error when it is and can't be read (a failed read is unknown:
|
||||
// a backup of it as nothing would say there was nothing).
|
||||
func Collect() (*Bundle, error) {
|
||||
if _, err := os.Stat(Path()); errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
f, err := view()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bundleOf(f), nil
|
||||
}
|
||||
|
||||
func bundleOf(f *file) *Bundle {
|
||||
b := &Bundle{Memories: f.Memories, Projects: f.Projects, Dismissed: f.Dismissed, Removed: f.Removed, Declined: f.Declined}
|
||||
return Combine(b, nil) // in order, the old deletions dropped
|
||||
}
|
||||
|
||||
// Hash is what tells a change in b: the memories, projects, dismissed
|
||||
// texts and deletions, but not when a search last returned a memory nor
|
||||
// how often (Used, Uses), which an agent's search changes and which
|
||||
// alone is no change worth a sync. A nil b hashes as "".
|
||||
func (b *Bundle) Hash() string {
|
||||
if b == nil {
|
||||
return ""
|
||||
}
|
||||
c := *b
|
||||
c.Memories = make([]*Memory, len(b.Memories))
|
||||
for i, m := range b.Memories {
|
||||
k := *m
|
||||
k.Used, k.Uses = time.Time{}, 0
|
||||
c.Memories[i] = &k
|
||||
}
|
||||
j, _ := json.Marshal(c)
|
||||
s := sha256.Sum256(j)
|
||||
return hex.EncodeToString(s[:])
|
||||
}
|
||||
|
||||
// Combine is a and b together, either nil, each memory once:
|
||||
// - of the same memory on both sides, the one changed later, unless
|
||||
// that change wasn't the user's (an agent's save, a tidy) and the
|
||||
// other is pinned or the user's (Fixed) while it isn't: what the
|
||||
// user made theirs is never written over by what a machine did on
|
||||
// another computer before it saw that;
|
||||
// - when a search last returned it and how often, the most of both;
|
||||
// - one deleted on either side stays deleted, unless it was changed
|
||||
// after the deletion;
|
||||
// - the projects, dismissed texts, deletions and suggestions turned
|
||||
// down of both.
|
||||
//
|
||||
// It is the same whichever side is a: memories by id, projects by key.
|
||||
func Combine(a, b *Bundle) *Bundle {
|
||||
if a == nil {
|
||||
a = &Bundle{}
|
||||
}
|
||||
if b == nil {
|
||||
b = &Bundle{}
|
||||
}
|
||||
out := &Bundle{Memories: []*Memory{}}
|
||||
cut := now().UTC().Add(-keepRemoved)
|
||||
for _, r := range []map[string]time.Time{a.Removed, b.Removed} {
|
||||
for id, t := range r {
|
||||
if t.Before(cut) {
|
||||
continue
|
||||
}
|
||||
if out.Removed == nil {
|
||||
out.Removed = map[string]time.Time{}
|
||||
}
|
||||
if t.After(out.Removed[id]) {
|
||||
out.Removed[id] = t
|
||||
}
|
||||
}
|
||||
}
|
||||
byID := map[string]*Memory{}
|
||||
for _, ms := range [][]*Memory{a.Memories, b.Memories} {
|
||||
for _, m := range ms {
|
||||
if m == nil || m.ID == "" {
|
||||
continue
|
||||
}
|
||||
if o := byID[m.ID]; o != nil {
|
||||
byID[m.ID] = pick(o, m)
|
||||
} else {
|
||||
c := *m
|
||||
byID[m.ID] = &c
|
||||
}
|
||||
}
|
||||
}
|
||||
for id, m := range byID {
|
||||
if t, ok := out.Removed[id]; ok && !m.Updated.After(t) {
|
||||
continue
|
||||
}
|
||||
out.Memories = append(out.Memories, m)
|
||||
}
|
||||
slices.SortFunc(out.Memories, func(x, y *Memory) int {
|
||||
return cmp.Or(x.Created.Compare(y.Created), cmp.Compare(x.ID, y.ID))
|
||||
})
|
||||
for _, ps := range []map[string]*Project{a.Projects, b.Projects} {
|
||||
for _, k := range slices.Sorted(maps.Keys(ps)) {
|
||||
p := ps[k]
|
||||
if p == nil {
|
||||
continue
|
||||
}
|
||||
if out.Projects == nil {
|
||||
out.Projects = map[string]*Project{}
|
||||
}
|
||||
o := out.Projects[k]
|
||||
if o == nil {
|
||||
c := *p
|
||||
c.Roots = slices.Clone(p.Roots)
|
||||
out.Projects[k] = &c
|
||||
continue
|
||||
}
|
||||
o.Name = max(o.Name, p.Name)
|
||||
o.Roots = append(o.Roots, p.Roots...)
|
||||
}
|
||||
}
|
||||
for _, p := range out.Projects {
|
||||
slices.Sort(p.Roots)
|
||||
p.Roots = slices.Compact(p.Roots)
|
||||
}
|
||||
// the dismissed texts in one order on every computer: the order they
|
||||
// were thrown away in is lost once two computers' are put together
|
||||
d := append(slices.Clone(a.Dismissed), b.Dismissed...)
|
||||
slices.Sort(d)
|
||||
if d = slices.Compact(d); len(d) > maxDismissed {
|
||||
d = d[len(d)-maxDismissed:]
|
||||
}
|
||||
if len(d) > 0 {
|
||||
out.Dismissed = d
|
||||
}
|
||||
n := append(slices.Clone(a.Declined), b.Declined...)
|
||||
slices.Sort(n)
|
||||
if n = slices.Compact(n); len(n) > maxDeclined {
|
||||
n = n[len(n)-maxDeclined:]
|
||||
}
|
||||
if len(n) > 0 {
|
||||
out.Declined = n
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// byUser is whether m's last change was the user's.
|
||||
func byUser(m *Memory) bool { return !m.Edited.IsZero() && m.Edited.Equal(m.Updated) }
|
||||
|
||||
// pick is the one of two copies of a memory that stays (Combine), as a copy.
|
||||
func pick(x, y *Memory) *Memory {
|
||||
newer, older := x, y
|
||||
if y.Updated.After(x.Updated) || y.Updated.Equal(x.Updated) && later(y, x) {
|
||||
newer, older = y, x
|
||||
}
|
||||
if !byUser(newer) && Fixed(older) && !Fixed(newer) {
|
||||
newer, older = older, newer
|
||||
}
|
||||
c := *newer
|
||||
if older.Used.After(c.Used) {
|
||||
c.Used = older.Used
|
||||
}
|
||||
c.Uses = max(c.Uses, older.Uses)
|
||||
return &c
|
||||
}
|
||||
|
||||
// later breaks a tie of two copies changed at the same time, the same way
|
||||
// on both computers.
|
||||
func later(x, y *Memory) bool {
|
||||
jx, _ := json.Marshal(x)
|
||||
jy, _ := json.Marshal(y)
|
||||
return string(jx) > string(jy)
|
||||
}
|
||||
|
||||
// Put merges b into memory here (Combine), writing memory.json only when
|
||||
// that changes it. It reports whether it did; a file here that can't be
|
||||
// read is an error, and nothing is written over it.
|
||||
func Put(b *Bundle) (changed bool, err error) {
|
||||
if b == nil {
|
||||
return false, nil
|
||||
}
|
||||
err = change(func(f *file) error {
|
||||
here := bundleOf(f)
|
||||
m := Combine(here, b)
|
||||
if m.Hash() == here.Hash() && sameUses(m, here) {
|
||||
return errSkip
|
||||
}
|
||||
f.Memories, f.Projects, f.Dismissed, f.Removed, f.Declined = m.Memories, m.Projects, m.Dismissed, m.Removed, m.Declined
|
||||
changed = true
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, errSkip) {
|
||||
err = nil
|
||||
}
|
||||
return changed, err
|
||||
}
|
||||
|
||||
// sameUses is whether a and b, the same memories, were used alike.
|
||||
func sameUses(a, b *Bundle) bool {
|
||||
return slices.EqualFunc(a.Memories, b.Memories, func(x, y *Memory) bool {
|
||||
return x.Used.Equal(y.Used) && x.Uses == y.Uses
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// two computers' memory.json, as Put and Collect see them: a test moves
|
||||
// between them by swapping Path
|
||||
type computer struct{ path string }
|
||||
|
||||
func (c computer) use(t *testing.T) {
|
||||
t.Helper()
|
||||
Path = func() string { return c.path }
|
||||
}
|
||||
|
||||
func twoComputers(t *testing.T) (a, b computer, at *time.Time) {
|
||||
at = fresh(t)
|
||||
a = computer{Path()}
|
||||
b = computer{t.TempDir() + "/memory.json"}
|
||||
return a, b, at
|
||||
}
|
||||
|
||||
// carry merges what from has into to, as a sync does.
|
||||
func carry(t *testing.T, from, to computer) bool {
|
||||
t.Helper()
|
||||
from.use(t)
|
||||
bun, err := Collect()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
to.use(t)
|
||||
changed, err := Put(bun)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
func texts(t *testing.T) map[string]*Memory {
|
||||
t.Helper()
|
||||
all, _, err := All()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := map[string]*Memory{}
|
||||
for _, m := range all {
|
||||
out[m.Text] = m
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSyncCarriesMemoriesBothWays(t *testing.T) {
|
||||
a, b, at := twoComputers(t)
|
||||
a.use(t)
|
||||
save(t, "Deploys go through mote", Procedure, Global)
|
||||
b.use(t)
|
||||
*at = at.Add(time.Minute)
|
||||
save(t, "Replies to users are in Chinese", Preference, Global)
|
||||
carry(t, a, b)
|
||||
carry(t, b, a)
|
||||
for _, c := range []computer{a, b} {
|
||||
c.use(t)
|
||||
if got := texts(t); len(got) != 2 {
|
||||
t.Fatalf("%s has %d memories, want both", c.path, len(got))
|
||||
}
|
||||
}
|
||||
// nothing new: nothing written
|
||||
if carry(t, a, b) || carry(t, b, a) {
|
||||
t.Fatal("a sync with nothing new changed memory.json")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncDeletionStaysDeleted(t *testing.T) {
|
||||
a, b, at := twoComputers(t)
|
||||
a.use(t)
|
||||
m := save(t, "Old fact", Fact, Global)
|
||||
carry(t, a, b)
|
||||
a.use(t)
|
||||
*at = at.Add(time.Minute)
|
||||
if err := Remove(m.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// b still has it: merged back, it stays gone on a, and goes from b
|
||||
carry(t, b, a)
|
||||
a.use(t)
|
||||
if _, ok := texts(t)["Old fact"]; ok {
|
||||
t.Fatal("a memory deleted here came back from a computer that had it")
|
||||
}
|
||||
carry(t, a, b)
|
||||
b.use(t)
|
||||
if _, ok := texts(t)["Old fact"]; ok {
|
||||
t.Fatal("the deletion didn't reach the other computer")
|
||||
}
|
||||
// a deletion remembered keepRemoved: after it, the record goes
|
||||
*at = at.Add(keepRemoved + time.Hour)
|
||||
a.use(t)
|
||||
bun, _ := Collect()
|
||||
if len(bun.Removed) != 0 {
|
||||
t.Fatalf("a deletion older than keepRemoved is still carried: %v", bun.Removed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncEditAfterDeletionKeepsIt(t *testing.T) {
|
||||
a, b, at := twoComputers(t)
|
||||
a.use(t)
|
||||
m := save(t, "Fact", Fact, Global)
|
||||
carry(t, a, b)
|
||||
a.use(t)
|
||||
*at = at.Add(time.Minute)
|
||||
if err := Remove(m.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.use(t)
|
||||
*at = at.Add(time.Minute)
|
||||
if _, err := Edit(m.ID, Input{Text: str("Fact, corrected")}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
carry(t, b, a)
|
||||
a.use(t)
|
||||
if _, ok := texts(t)["Fact, corrected"]; !ok {
|
||||
t.Fatal("an edit made after the deletion elsewhere was lost")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncLaterChangeWins(t *testing.T) {
|
||||
a, b, at := twoComputers(t)
|
||||
a.use(t)
|
||||
m := save(t, "Tabs", Preference, Global)
|
||||
carry(t, a, b)
|
||||
a.use(t)
|
||||
*at = at.Add(time.Minute)
|
||||
Edit(m.ID, Input{Text: str("Tabs, width 4")}, true)
|
||||
b.use(t)
|
||||
*at = at.Add(time.Minute)
|
||||
Edit(m.ID, Input{Text: str("Tabs, width 8")}, true)
|
||||
carry(t, a, b)
|
||||
carry(t, b, a)
|
||||
for _, c := range []computer{a, b} {
|
||||
c.use(t)
|
||||
got := texts(t)
|
||||
if _, ok := got["Tabs, width 8"]; !ok || len(got) != 1 {
|
||||
t.Fatalf("%s: %v, want the later edit alone", c.path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A tidy on one computer, later than the user's pin on the other but
|
||||
// before it saw the pin, never sets the user's memory aside.
|
||||
func TestSyncMachineChangeNeverOverUsersOwn(t *testing.T) {
|
||||
a, b, at := twoComputers(t)
|
||||
a.use(t)
|
||||
m := save(t, "Use mote for builds", Rule, Global)
|
||||
carry(t, a, b)
|
||||
b.use(t)
|
||||
*at = at.Add(time.Minute)
|
||||
pin := true
|
||||
Edit(m.ID, Input{Pinned: &pin}, true)
|
||||
a.use(t)
|
||||
*at = at.Add(time.Minute)
|
||||
if _, err := Forget(m.ID); err != nil { // not the user's: an agent's forget
|
||||
t.Fatal(err)
|
||||
}
|
||||
carry(t, a, b)
|
||||
carry(t, b, a)
|
||||
for _, c := range []computer{a, b} {
|
||||
c.use(t)
|
||||
got := texts(t)["Use mote for builds"]
|
||||
if got == nil || !got.Pinned || got.Status != Active {
|
||||
t.Fatalf("%s: %+v, want the pinned memory active", c.path, got)
|
||||
}
|
||||
}
|
||||
// the user unpinning it later is theirs, and goes everywhere
|
||||
*at = at.Add(time.Minute)
|
||||
pin = false
|
||||
Edit(m.ID, Input{Pinned: &pin}, true)
|
||||
carry(t, b, a)
|
||||
a.use(t)
|
||||
if texts(t)["Use mote for builds"].Pinned {
|
||||
t.Fatal("the user's unpin didn't go to the other computer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncKeepsMostUses(t *testing.T) {
|
||||
a, b, at := twoComputers(t)
|
||||
a.use(t)
|
||||
m := save(t, "Fact", Fact, Global)
|
||||
carry(t, a, b)
|
||||
a.use(t)
|
||||
*at = at.Add(2 * time.Minute)
|
||||
touch([]string{m.ID})
|
||||
if !carry(t, a, b) {
|
||||
t.Fatal("uses from the other computer weren't taken")
|
||||
}
|
||||
if got := texts(t)["Fact"]; got.Uses != 1 || !got.Used.Equal(*at) {
|
||||
t.Fatalf("%+v, want a's use", got)
|
||||
}
|
||||
// a use alone is no change to sync
|
||||
a.use(t)
|
||||
x, _ := Collect()
|
||||
*at = at.Add(2 * time.Minute)
|
||||
touch([]string{m.ID})
|
||||
y, _ := Collect()
|
||||
if x.Hash() != y.Hash() {
|
||||
t.Fatal("a search changed what tells a sync something changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCombineIsTheSameEitherWay(t *testing.T) {
|
||||
t0 := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
|
||||
fresh(t)
|
||||
a := &Bundle{
|
||||
Memories: []*Memory{{ID: "m_1", Text: "x", Updated: t0}, {ID: "m_2", Text: "y", Updated: t0}},
|
||||
Projects: map[string]*Project{"p": {Key: "p", Name: "p", Roots: []string{"/a"}}},
|
||||
Dismissed: []string{"b", "a"},
|
||||
}
|
||||
b := &Bundle{
|
||||
Memories: []*Memory{{ID: "m_1", Text: "x2", Updated: t0}, {ID: "m_3", Text: "z", Updated: t0}},
|
||||
Projects: map[string]*Project{"p": {Key: "p", Name: "q", Roots: []string{"C:\\a"}}},
|
||||
Dismissed: []string{"c"},
|
||||
Removed: map[string]time.Time{"m_2": t0.Add(time.Hour)},
|
||||
}
|
||||
x, y := Combine(a, b), Combine(b, a)
|
||||
if x.Hash() != y.Hash() {
|
||||
t.Fatal("Combine(a, b) differs from Combine(b, a)")
|
||||
}
|
||||
if len(x.Memories) != 2 || len(x.Projects["p"].Roots) != 2 || len(x.Dismissed) != 3 {
|
||||
t.Fatalf("merged %+v", x)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectUnreadableIsAnError(t *testing.T) {
|
||||
fresh(t)
|
||||
if b, err := Collect(); b != nil || err != nil {
|
||||
t.Fatalf("no memory.json: %v, %v; want nothing", b, err)
|
||||
}
|
||||
if err := os.WriteFile(Path(), []byte("{not json"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Collect(); err == nil {
|
||||
t.Fatal("an unreadable memory.json was collected")
|
||||
}
|
||||
if _, err := Put(&Bundle{Memories: []*Memory{{ID: "m_1", Text: "x"}}}); err == nil {
|
||||
t.Fatal("a sync wrote over an unreadable memory.json")
|
||||
}
|
||||
}
|
||||
@@ -189,7 +189,13 @@ func Untidy(cs []Change) (int, error) {
|
||||
}
|
||||
}
|
||||
if c.New {
|
||||
f.Memories = slices.DeleteFunc(f.Memories, func(m *Memory) bool { return m.ID == c.Into && !Fixed(m) })
|
||||
f.Memories = slices.DeleteFunc(f.Memories, func(m *Memory) bool {
|
||||
if m.ID == c.Into && !Fixed(m) {
|
||||
removed(f, m.ID)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
Reference in New Issue
Block a user