build: 内置 norma 模块,构建不再依赖上游仓库
把 github.com/Autumn-27/norma v0.4.3(commit 320ae32)的源码复制到 third_party/norma,并用 go.mod 的 replace 指向本地副本。上游删除仓库或 改写 tag 都不再影响本仓库构建。 - 已验证 GOPROXY=off 下可完整编译并打出发行包 - go.sum 中该模块的两条校验记录随之删除(本地 replace 不需要哈希) - 升级方法与授权注意事项见 third_party/README.md
This commit is contained in:
1 parent
a819fa3230
commit
f782b612ec
213 files changed
+37401
-2
No files matched your search
Vendored
+191
@@ -0,0 +1,191 @@
|
||||
// Package memory gives the agent persistent, file-backed long-term memory.
|
||||
// Each memory is a markdown file with YAML frontmatter
|
||||
// (name / description / type) in a memory directory; a MEMORY.md index lists
|
||||
// them. The agent recalls memories relevant to a query and records new ones via
|
||||
// tools, and relevant memories can be auto-injected into the conversation.
|
||||
package memory
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Type classifies a memory.
|
||||
type Type string
|
||||
|
||||
const (
|
||||
TypeUser Type = "user" // facts about the user (role, preferences)
|
||||
TypeFeedback Type = "feedback" // guidance on how the agent should work
|
||||
TypeProject Type = "project" // ongoing work, goals, constraints
|
||||
TypeReference Type = "reference" // pointers to external resources
|
||||
)
|
||||
|
||||
// Memory is a single stored fact.
|
||||
type Memory struct {
|
||||
Name string
|
||||
Description string
|
||||
Type Type
|
||||
Content string
|
||||
Path string
|
||||
ModTime time.Time
|
||||
}
|
||||
|
||||
// Store is a memory directory.
|
||||
type Store struct {
|
||||
Dir string
|
||||
}
|
||||
|
||||
// NewStore roots a store at dir (created on first write).
|
||||
func NewStore(dir string) *Store { return &Store{Dir: dir} }
|
||||
|
||||
const indexFile = "MEMORY.md"
|
||||
|
||||
func (s *Store) ensure() error { return os.MkdirAll(s.Dir, 0o755) }
|
||||
|
||||
var slugRe = regexp.MustCompile(`[^a-z0-9]+`)
|
||||
|
||||
func slug(name string) string {
|
||||
s := slugRe.ReplaceAllString(strings.ToLower(name), "-")
|
||||
return strings.Trim(s, "-")
|
||||
}
|
||||
|
||||
// Scan reads every memory file (excluding the index), newest first.
|
||||
func (s *Store) Scan() ([]Memory, error) {
|
||||
entries, err := os.ReadDir(s.Dir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var out []Memory
|
||||
for _, e := range entries {
|
||||
if e.IsDir() || e.Name() == indexFile || !strings.HasSuffix(e.Name(), ".md") {
|
||||
continue
|
||||
}
|
||||
m, err := s.readFile(filepath.Join(s.Dir, e.Name()))
|
||||
if err == nil {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ModTime.After(out[j].ModTime) })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Read returns the memory with the given name (or its slug).
|
||||
func (s *Store) Read(name string) (Memory, error) {
|
||||
p := filepath.Join(s.Dir, slug(name)+".md")
|
||||
return s.readFile(p)
|
||||
}
|
||||
|
||||
func (s *Store) readFile(path string) (Memory, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return Memory{}, err
|
||||
}
|
||||
m := parseFrontmatter(string(data))
|
||||
m.Path = path
|
||||
if m.Name == "" {
|
||||
m.Name = strings.TrimSuffix(filepath.Base(path), ".md")
|
||||
}
|
||||
if info, e := os.Stat(path); e == nil {
|
||||
m.ModTime = info.ModTime()
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Save writes a memory file and rebuilds the MEMORY.md index.
|
||||
func (s *Store) Save(m Memory) error {
|
||||
if err := s.ensure(); err != nil {
|
||||
return err
|
||||
}
|
||||
if m.Name == "" {
|
||||
return fmt.Errorf("memory: name is required")
|
||||
}
|
||||
path := filepath.Join(s.Dir, slug(m.Name)+".md")
|
||||
if err := os.WriteFile(path, []byte(renderFrontmatter(m)), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.rebuildIndex()
|
||||
}
|
||||
|
||||
// Index returns the MEMORY.md content (an index of memories), building it from a
|
||||
// scan if the file is absent.
|
||||
func (s *Store) Index() string {
|
||||
if data, err := os.ReadFile(filepath.Join(s.Dir, indexFile)); err == nil {
|
||||
return string(data)
|
||||
}
|
||||
return s.buildIndex()
|
||||
}
|
||||
|
||||
func (s *Store) rebuildIndex() error {
|
||||
return os.WriteFile(filepath.Join(s.Dir, indexFile), []byte(s.buildIndex()), 0o644)
|
||||
}
|
||||
|
||||
func (s *Store) buildIndex() string {
|
||||
mems, _ := s.Scan()
|
||||
var b strings.Builder
|
||||
b.WriteString("# Memory\n\n")
|
||||
if len(mems) == 0 {
|
||||
b.WriteString("(no memories yet)\n")
|
||||
return b.String()
|
||||
}
|
||||
for _, m := range mems {
|
||||
fmt.Fprintf(&b, "- [%s](%s.md) — %s\n", m.Name, slug(m.Name), m.Description)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// parseFrontmatter extracts name/description/type and the body from a markdown
|
||||
// file with optional YAML frontmatter.
|
||||
func parseFrontmatter(s string) Memory {
|
||||
var m Memory
|
||||
if strings.HasPrefix(s, "---") {
|
||||
rest := strings.TrimPrefix(s, "---")
|
||||
rest = strings.TrimLeft(rest, "\r\n")
|
||||
if i := strings.Index(rest, "\n---"); i >= 0 {
|
||||
head := rest[:i]
|
||||
body := rest[i+len("\n---"):]
|
||||
body = strings.TrimLeft(body, "-")
|
||||
m.Content = strings.TrimLeft(body, "\r\n")
|
||||
for _, line := range strings.Split(head, "\n") {
|
||||
k, v, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
k = strings.TrimSpace(k)
|
||||
v = strings.TrimSpace(v)
|
||||
switch k {
|
||||
case "name":
|
||||
m.Name = v
|
||||
case "description":
|
||||
m.Description = v
|
||||
case "type":
|
||||
m.Type = Type(v)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
}
|
||||
m.Content = s
|
||||
return m
|
||||
}
|
||||
|
||||
func renderFrontmatter(m Memory) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("---\n")
|
||||
fmt.Fprintf(&b, "name: %s\n", m.Name)
|
||||
fmt.Fprintf(&b, "description: %s\n", m.Description)
|
||||
if m.Type != "" {
|
||||
fmt.Fprintf(&b, "type: %s\n", m.Type)
|
||||
}
|
||||
b.WriteString("---\n\n")
|
||||
b.WriteString(strings.TrimRight(m.Content, "\n"))
|
||||
b.WriteString("\n")
|
||||
return b.String()
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
func TestSaveScanReadRelevant(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
if err := s.Save(Memory{Name: "User Role", Description: "the user's job", Type: TypeUser, Content: "The user is a Go backend engineer."}); err != nil {
|
||||
t.Fatalf("save: %v", err)
|
||||
}
|
||||
if err := s.Save(Memory{Name: "Test Policy", Description: "how to test", Type: TypeFeedback, Content: "Always run go test before claiming done."}); err != nil {
|
||||
t.Fatalf("save: %v", err)
|
||||
}
|
||||
|
||||
mems, _ := s.Scan()
|
||||
if len(mems) != 2 {
|
||||
t.Fatalf("scan=%d", len(mems))
|
||||
}
|
||||
|
||||
// Frontmatter round-trips.
|
||||
m, err := s.Read("User Role")
|
||||
if err != nil || m.Type != TypeUser || !strings.Contains(m.Content, "backend engineer") {
|
||||
t.Fatalf("read: %+v err=%v", m, err)
|
||||
}
|
||||
|
||||
// Index lists both with a slug link.
|
||||
idx := s.Index()
|
||||
if !strings.Contains(idx, "[User Role](user-role.md)") || !strings.Contains(idx, "Test Policy") {
|
||||
t.Fatalf("index:\n%s", idx)
|
||||
}
|
||||
|
||||
// Relevance picks the role memory for a role query.
|
||||
rel := s.Relevant("what is the user's role and job", 5)
|
||||
if len(rel) == 0 || rel[0].Name != "User Role" {
|
||||
t.Fatalf("relevant: %+v", rel)
|
||||
}
|
||||
|
||||
// On-disk file has YAML frontmatter.
|
||||
data, _ := os.ReadFile(filepath.Join(s.Dir, "user-role.md"))
|
||||
if !strings.HasPrefix(string(data), "---\nname: User Role") {
|
||||
t.Fatalf("frontmatter:\n%s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryTools(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
rec, recall := RecordTool(s), RecallTool(s)
|
||||
|
||||
res, _ := rec.Call(context.Background(), []byte(`{"name":"Deploy","description":"how to deploy","type":"project","content":"Deploy via make release."}`), &tool.ToolContext{})
|
||||
if res.IsError {
|
||||
t.Fatalf("record: %q", res.Flatten())
|
||||
}
|
||||
res, _ = recall.Call(context.Background(), []byte(`{"query":"how do I deploy"}`), &tool.ToolContext{})
|
||||
if !strings.Contains(res.Flatten(), "make release") {
|
||||
t.Fatalf("recall: %q", res.Flatten())
|
||||
}
|
||||
}
|
||||
Vendored
+130
@@ -0,0 +1,130 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var wordRe = regexp.MustCompile(`[a-z0-9_]+`)
|
||||
|
||||
var stop = map[string]bool{
|
||||
"the": true, "a": true, "an": true, "and": true, "or": true, "of": true,
|
||||
"to": true, "in": true, "is": true, "it": true, "for": true, "on": true,
|
||||
"do": true, "i": true, "you": true, "my": true, "me": true, "what": true,
|
||||
"how": true, "can": true, "with": true, "this": true, "that": true,
|
||||
}
|
||||
|
||||
func tokenize(s string) []string {
|
||||
words := wordRe.FindAllString(strings.ToLower(s), -1)
|
||||
var out []string
|
||||
for _, w := range words {
|
||||
if len(w) >= 2 && !stop[w] {
|
||||
out = append(out, w)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func score(m Memory, tokens []string) int {
|
||||
name := strings.ToLower(m.Name + " " + string(m.Type))
|
||||
desc := strings.ToLower(m.Description)
|
||||
body := strings.ToLower(m.Content)
|
||||
s := 0
|
||||
for _, t := range tokens {
|
||||
if strings.Contains(name, t) {
|
||||
s += 3
|
||||
}
|
||||
if strings.Contains(desc, t) {
|
||||
s += 2
|
||||
}
|
||||
if strings.Contains(body, t) {
|
||||
s++
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Relevant returns up to max memories scored against the query (keyword match on
|
||||
// name/description/content), most relevant first, recency breaking ties.
|
||||
func (s *Store) Relevant(query string, max int) []Memory {
|
||||
mems, _ := s.Scan()
|
||||
tokens := tokenize(query)
|
||||
if len(tokens) == 0 {
|
||||
return nil
|
||||
}
|
||||
type sc struct {
|
||||
m Memory
|
||||
s int
|
||||
}
|
||||
var ranked []sc
|
||||
for _, m := range mems {
|
||||
if v := score(m, tokens); v > 0 {
|
||||
ranked = append(ranked, sc{m, v})
|
||||
}
|
||||
}
|
||||
sort.SliceStable(ranked, func(i, j int) bool {
|
||||
if ranked[i].s != ranked[j].s {
|
||||
return ranked[i].s > ranked[j].s
|
||||
}
|
||||
return ranked[i].m.ModTime.After(ranked[j].m.ModTime)
|
||||
})
|
||||
out := make([]Memory, 0, max)
|
||||
for i, r := range ranked {
|
||||
if max > 0 && i >= max {
|
||||
break
|
||||
}
|
||||
out = append(out, r.m)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Age renders a human age like "today" / "yesterday" / "5 days ago".
|
||||
func Age(m Memory, now time.Time) string {
|
||||
if m.ModTime.IsZero() {
|
||||
return "unknown age"
|
||||
}
|
||||
days := int(now.Sub(m.ModTime).Hours() / 24)
|
||||
switch {
|
||||
case days <= 0:
|
||||
return "today"
|
||||
case days == 1:
|
||||
return "yesterday"
|
||||
default:
|
||||
return fmt.Sprintf("%d days ago", days)
|
||||
}
|
||||
}
|
||||
|
||||
// stalenessNote returns a caveat for memories older than a day, or "" if fresh.
|
||||
func stalenessNote(m Memory, now time.Time) string {
|
||||
if m.ModTime.IsZero() || now.Sub(m.ModTime).Hours() < 48 {
|
||||
return ""
|
||||
}
|
||||
return "(This memory is a point-in-time note, not live state — verify claims about code against the current source before relying on them.)"
|
||||
}
|
||||
|
||||
// SystemSegment renders the memory index for inclusion in the system prompt so
|
||||
// the agent knows what it remembers and can RecallMemory for details.
|
||||
func (s *Store) SystemSegment() string {
|
||||
return "# Memory\nYou have persistent long-term memory. Index of saved memories — call RecallMemory to read full content, and RecordMemory to save a durable fact:\n\n" + s.Index()
|
||||
}
|
||||
|
||||
// RenderForInjection formats memories as context to inject before a user turn.
|
||||
func RenderForInjection(mems []Memory, now time.Time) string {
|
||||
if len(mems) == 0 {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("Relevant memories (saved earlier):\n")
|
||||
for _, m := range mems {
|
||||
fmt.Fprintf(&b, "\n--- %s (saved %s) ---\n", m.Name, Age(m, now))
|
||||
if note := stalenessNote(m, now); note != "" {
|
||||
b.WriteString(note + "\n")
|
||||
}
|
||||
b.WriteString(strings.TrimSpace(m.Content))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
Vendored
+91
@@ -0,0 +1,91 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/norma/permission"
|
||||
"github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
// Tools returns the RecallMemory and RecordMemory tools bound to a store.
|
||||
func Tools(s *Store) []tool.CoreTool {
|
||||
return []tool.CoreTool{RecallTool(s), RecordTool(s)}
|
||||
}
|
||||
|
||||
// RecallTool lets the agent read memories relevant to a query.
|
||||
func RecallTool(s *Store) tool.CoreTool {
|
||||
return tool.Build(tool.Spec{
|
||||
Name: "RecallMemory",
|
||||
Description: "Searches your long-term memory for facts relevant to a query and returns their full content. Use it when prior context (user preferences, project state, past decisions) would help.",
|
||||
Schema: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{"query": map[string]any{"type": "string", "description": "What to recall."}},
|
||||
"required": []any{"query"},
|
||||
},
|
||||
ReadOnly: func(json.RawMessage) bool { return true },
|
||||
Concurrent: func(json.RawMessage) bool { return true },
|
||||
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
|
||||
return permission.Allowed()
|
||||
},
|
||||
Run: func(_ context.Context, input json.RawMessage, _ *tool.ToolContext) (tool.Result, error) {
|
||||
var in struct {
|
||||
Query string `json:"query"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return tool.Result{}, err
|
||||
}
|
||||
mems := s.Relevant(in.Query, 5)
|
||||
if len(mems) == 0 {
|
||||
return tool.Text("No relevant memories found."), nil
|
||||
}
|
||||
return tool.Text(RenderForInjection(mems, time.Now())), nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// RecordTool lets the agent persist a durable fact to memory.
|
||||
func RecordTool(s *Store) tool.CoreTool {
|
||||
return tool.Build(tool.Spec{
|
||||
Name: "RecordMemory",
|
||||
Description: "Saves a durable fact to long-term memory so it persists across sessions. Record stable facts (user preferences, project constraints, decisions) — not transient conversation detail.",
|
||||
Prompt: "type is one of: user (about the user), feedback (how you should work), project (ongoing work/constraints), reference (external resources). Give a short name and a one-line description.",
|
||||
Schema: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"name": map[string]any{"type": "string", "description": "Short title for the memory."},
|
||||
"description": map[string]any{"type": "string", "description": "One-line summary."},
|
||||
"type": map[string]any{"type": "string", "description": "user | feedback | project | reference"},
|
||||
"content": map[string]any{"type": "string", "description": "The fact to remember (markdown)."},
|
||||
},
|
||||
"required": []any{"name", "content"},
|
||||
},
|
||||
ReadOnly: func(json.RawMessage) bool { return false },
|
||||
Concurrent: func(json.RawMessage) bool { return false },
|
||||
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
|
||||
return permission.Allowed()
|
||||
},
|
||||
Run: func(_ context.Context, input json.RawMessage, _ *tool.ToolContext) (tool.Result, error) {
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return tool.Result{}, err
|
||||
}
|
||||
if strings.TrimSpace(in.Name) == "" || strings.TrimSpace(in.Content) == "" {
|
||||
return tool.Errorf("Error: name and content are required"), nil
|
||||
}
|
||||
m := Memory{Name: in.Name, Description: in.Description, Type: Type(in.Type), Content: in.Content}
|
||||
if err := s.Save(m); err != nil {
|
||||
return tool.Errorf("Error saving memory: " + err.Error()), nil
|
||||
}
|
||||
return tool.Text(fmt.Sprintf("Saved memory %q.", in.Name)), nil
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user