返回 DeepSeek-Reasonix
store.go
根目录 / internal / memory / store.go
1 package memory
2
3 import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "regexp"
8 "sort"
9 "strconv"
10 "strings"
11 "time"
12
13 "reasonix/internal/config"
14 "reasonix/internal/fileutil"
15 fileencoding "reasonix/internal/fileutil/encoding"
16 "reasonix/internal/frontmatter"
17 )
18
19 // Store is the scoped auto-memory store: project and global directories of
20 // one-fact-per-file Markdown notes, each with a MEMORY.md index.
21 // The model maintains it through the `remember` tool; the index loads into the
22 // cached system-prompt prefix at boot so the model always knows what it has
23 // saved, and reads individual facts on demand with the `memory` tool. The whole
24 // thing is plain files the user can edit by hand.
25 //
26 // Scope and type are independent: callers choose whether a fact belongs to the
27 // current project or every project, while Type only classifies its contents.
28 // List() and Index() merge both directories so every session sees the full set.
29 type Store struct {
30 Dir string // ...reasonix/projects/<project directory>/memory
31 GlobalDir string // ...reasonix/memory/global (shared across projects)
32 }
33
34 // Type classifies a memory, mirroring the auto-memory taxonomy.
35 type Type string
36
37 const (
38 TypeUser Type = "user" // who the user is: role, preferences, expertise
39 TypeFeedback Type = "feedback" // guidance on how to work (with why + how-to-apply)
40 TypeProject Type = "project" // ongoing work / goals / constraints not in the code
41 TypeReference Type = "reference" // pointers to external resources (URLs, tickets)
42 )
43
44 // validTypes is the closed set the `remember` tool accepts; anything else
45 // normalises to TypeProject.
46 var validTypes = map[Type]bool{TypeUser: true, TypeFeedback: true, TypeProject: true, TypeReference: true}
47
48 // NormalizeType coerces an arbitrary string to a known Type, defaulting to
49 // TypeProject so a sloppy tool argument never blocks a save.
50 func NormalizeType(s string) Type {
51 t := Type(strings.ToLower(strings.TrimSpace(s)))
52 if validTypes[t] {
53 return t
54 }
55 return TypeProject
56 }
57
58 // FactScope controls where an auto-memory fact is active. It is intentionally
59 // separate from Type: project feedback should not silently become global merely
60 // because it is classified as feedback.
61 type FactScope string
62
63 const (
64 FactScopeProject FactScope = "project"
65 FactScopeGlobal FactScope = "global"
66 )
67
68 // NormalizeFactScope defaults to the current project. Global memory must be an
69 // explicit choice because it affects every workspace.
70 func NormalizeFactScope(s string) FactScope {
71 if FactScope(strings.ToLower(strings.TrimSpace(s))) == FactScopeGlobal {
72 return FactScopeGlobal
73 }
74 return FactScopeProject
75 }
76
77 // Memory is one stored fact.
78 type Memory struct {
79 ID string // immutable identity; Name may change without changing ID
80 Revision int // monotonic content revision, starting at 1
81 CreatedAt time.Time
82 UpdatedAt time.Time
83 Name string // kebab-case slug; also the file stem (<name>.md)
84 Title string // human-readable index label; falls back to a de-kebabed Name
85 Description string // one-line summary used for the index and recall
86 Type Type
87 Scope FactScope // project by default; global only when explicitly requested
88 Activation Activation // persisted choice; "" = unset, resolved by ResolveActivation
89 Volatility Volatility // how fast the fact ages; "" = unset, type default applies
90 SubjectKey string // which question the fact answers (project.package_manager); one active value per scope+subject
91 ExpiresAt time.Time // hard freshness boundary; zero = never expires
92 LastVerifiedAt time.Time // last explicit confirmation; renews the freshness clock
93 Keywords string // search aliases (bilingual synonyms, related commands); recall-only, never rendered into the index
94 Body string // the fact itself (Markdown)
95 }
96
97 // ArchivedMemory is a saved fact that has been removed from active memory but
98 // kept on disk for traceability.
99 type ArchivedMemory struct {
100 Memory
101 Path string
102 ArchivedAt time.Time
103 }
104
105 // StoreFor resolves the auto-memory directory for a project working dir under
106 // Reasonix home, e.g. ~/.reasonix/projects/-Users-me-proj/memory.
107 // A "" userDir (config dir unresolvable) yields a zero Store, which all methods
108 // treat as a disabled no-op.
109 func StoreFor(userDir, cwd string) Store {
110 if userDir == "" {
111 return Store{}
112 }
113 return Store{
114 Dir: filepath.Join(config.ProjectStateDir(userDir, absOf(cwd)), "memory"),
115 GlobalDir: filepath.Join(userDir, "memory", "global"),
116 }
117 }
118
119 // DirFor returns the directory for an explicit fact scope. When GlobalDir is
120 // unavailable, global writes fall back to Dir rather than being dropped.
121 func (s Store) DirFor(scope FactScope) string {
122 if s.GlobalDir != "" && NormalizeFactScope(string(scope)) == FactScopeGlobal {
123 return s.GlobalDir
124 }
125 return s.Dir
126 }
127
128 // indexFile is the human-readable index of saved memories.
129 const indexFile = "MEMORY.md"
130
131 // dirs returns the directories to read from, in order: GlobalDir first (shared
132 // memories), then Dir (project-specific).
133 func (s Store) dirs() []string {
134 if s.GlobalDir != "" && s.GlobalDir != s.Dir {
135 return []string{s.GlobalDir, s.Dir}
136 }
137 return []string{s.Dir}
138 }
139
140 // Path returns the absolute file path a memory with the given name lives at.
141 // It checks GlobalDir first, then Dir, returning the first match. If no file
142 // exists yet, it returns the path in Dir (the default project scope).
143 func (s Store) Path(name string) string {
144 if _, path, ok := s.findActive(name); ok {
145 return path
146 }
147 ref := parseMemoryReference(name)
148 stem := ref.name + ".md"
149 if ref.qualified {
150 p, err := safeJoin(s.DirFor(ref.scope), stem)
151 if err != nil {
152 return ""
153 }
154 return p
155 }
156 for _, dir := range s.dirs() {
157 if dir == "" {
158 continue
159 }
160 p, err := safeJoin(dir, stem)
161 if err != nil {
162 continue
163 }
164 if _, err := os.Stat(p); err == nil {
165 return p
166 }
167 }
168 p, sjErr := safeJoin(s.Dir, stem)
169 if sjErr != nil {
170 return ""
171 }
172 return p
173 }
174
175 // Save writes (or overwrites) a memory file and refreshes its MEMORY.md index
176 // line. It is the single mutation entry point — the `remember` tool, the desktop
177 // editor, and any future importer all go through here so the index never drifts
178 // from the files. Returns the path written.
179 func (s Store) Save(m Memory) (string, error) {
180 result, err := s.SaveWithOptions(m, SaveOptions{})
181 return result.Path, err
182 }
183
184 // Archive removes a memory from the active store and moves its file under
185 // .archive/ for traceability. A missing file is not an error; the goal state
186 // (not active) already holds. It returns the archive path, or "" when no file
187 // existed to archive.
188 // When both GlobalDir and Dir exist, it archives from every directory the
189 // memory appears in (handles migration duplicates).
190 func (s Store) Archive(name string) (string, error) {
191 memoryStoreMutationMu.Lock()
192 defer memoryStoreMutationMu.Unlock()
193 return s.archiveLocked(name)
194 }
195
196 func (s Store) archiveLocked(name string) (string, error) {
197 if s.Dir == "" && s.GlobalDir == "" {
198 return "", fmt.Errorf("memory store unavailable (no user config dir)")
199 }
200 ref := strings.TrimSpace(name)
201 parsed := parseMemoryReference(ref)
202 if active, path, ok := s.findActive(ref); ok && ref == active.ID {
203 return s.archiveByID(active.Name, ref)
204 } else if ok && parsed.qualified {
205 return archiveMemoryInDir(filepath.Dir(path), active.Name)
206 } else if ok {
207 name = active.Name
208 } else if parsed.qualified {
209 if parsed.name == "" {
210 return "", fmt.Errorf("memory needs a name")
211 }
212 return archiveMemoryInDir(s.DirFor(parsed.scope), parsed.name)
213 } else {
214 name = slug(name)
215 }
216 if name == "" {
217 return "", fmt.Errorf("memory needs a name")
218 }
219 var lastPath string
220 for _, dir := range s.dirs() {
221 if dir == "" {
222 continue
223 }
224 lines, contains, err := indexLinesExceptIn(dir, name)
225 if err != nil {
226 return "", err
227 }
228 p, err := archiveInDir(dir, name)
229 if err != nil {
230 return "", err
231 }
232 if p != "" || contains {
233 if err := flushIndexIn(dir, lines); err != nil {
234 return "", err
235 }
236 }
237 if p != "" {
238 lastPath = p
239 }
240 }
241 return lastPath, nil
242 }
243
244 func archiveMemoryInDir(dir, name string) (string, error) {
245 lines, contains, err := indexLinesExceptIn(dir, name)
246 if err != nil {
247 return "", err
248 }
249 path, err := archiveInDir(dir, name)
250 if err != nil {
251 return "", err
252 }
253 if path != "" || contains {
254 if err := flushIndexIn(dir, lines); err != nil {
255 return "", err
256 }
257 }
258 return path, nil
259 }
260
261 // Delete removes a memory from the active store and its MEMORY.md line — the
262 // model's `forget` path and the user's way to prune a stale fact. It archives
263 // the file instead of permanently deleting it so wrong memories remain
264 // traceable. A missing file is not an error; the goal state (gone) holds either
265 // way.
266 func (s Store) Delete(name string) error {
267 _, err := s.Archive(name)
268 return err
269 }
270
271 func archiveInDir(dir, name string) (string, error) {
272 root, err := os.OpenRoot(dir)
273 if os.IsNotExist(err) {
274 return "", nil
275 }
276 if err != nil {
277 return "", err
278 }
279 defer root.Close()
280
281 file := name + ".md"
282 if _, err := root.Stat(file); err != nil {
283 if os.IsNotExist(err) {
284 return "", nil
285 }
286 return "", err
287 }
288 if err := root.MkdirAll(".archive", 0o755); err != nil {
289 return "", err
290 }
291 dest, err := archivePath(root, name, time.Now().UTC())
292 if err != nil {
293 return "", err
294 }
295 if err := renameMemoryFile(root, file, dest); err != nil {
296 return "", err
297 }
298 out, err := safeJoin(dir, dest)
299 if err != nil {
300 return "", err
301 }
302 return out, nil
303 }
304
305 func archivePath(root *os.Root, name string, when time.Time) (string, error) {
306 stem := when.Format("20060102-150405.000") + "-" + name
307 path := filepath.Join(".archive", stem+".md")
308 if _, err := root.Stat(path); os.IsNotExist(err) {
309 return path, nil
310 } else if err != nil {
311 return "", err
312 }
313 for i := 1; ; i++ {
314 path = filepath.Join(".archive", fmt.Sprintf("%s-%d.md", stem, i))
315 if _, err := root.Stat(path); os.IsNotExist(err) {
316 return path, nil
317 } else if err != nil {
318 return "", err
319 }
320 }
321 }
322
323 func safeJoin(base, name string) (string, error) {
324 if base == "" {
325 return "", fmt.Errorf("memory store unavailable (no user config dir)")
326 }
327 if !filepath.IsLocal(name) {
328 return "", fmt.Errorf("memory path escapes store: %s", name)
329 }
330 baseAbs, err := filepath.Abs(base)
331 if err != nil {
332 return "", err
333 }
334 path := filepath.Join(baseAbs, name)
335 pathAbs, err := filepath.Abs(path)
336 if err != nil {
337 return "", err
338 }
339 rel, err := filepath.Rel(baseAbs, pathAbs)
340 if err != nil {
341 return "", err
342 }
343 if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) || filepath.IsAbs(rel) {
344 return "", fmt.Errorf("memory path escapes store: %s", name)
345 }
346 return pathAbs, nil
347 }
348
349 func renameMemoryFile(root *os.Root, path, dest string) error {
350 err := root.Rename(path, dest)
351 if err == nil || os.IsNotExist(err) {
352 return nil
353 }
354 if !os.IsPermission(err) {
355 return err
356 }
357 repairOwnerWrite(root, path, false)
358 repairOwnerWrite(root, filepath.Dir(path), true)
359 repairOwnerWrite(root, filepath.Dir(dest), true)
360 err = root.Rename(path, dest)
361 if err == nil || os.IsNotExist(err) {
362 return nil
363 }
364 return err
365 }
366
367 func repairOwnerWrite(root *os.Root, path string, dir bool) {
368 info, err := root.Stat(path)
369 if err != nil {
370 return
371 }
372 need := os.FileMode(0o600)
373 if dir {
374 need = 0o700
375 }
376 _ = root.Chmod(path, info.Mode().Perm()|need)
377 }
378
379 // indexLineRe matches a managed index line so reindex/Delete can target the line
380 // for one memory by its filename without disturbing the rest of a hand-edited
381 // MEMORY.md.
382 var indexLineRe = regexp.MustCompile(`(?m)^\s*-\s\[.+?\]\(([^)]+)\.md\)\s*—\s.*$`)
383
384 // flushIndexIn rewrites MEMORY.md in the given directory from the managed lines,
385 // preserving hand-written content. Managed lines are updated or removed, and
386 // new managed entries are appended in sorted order.
387 func flushIndexIn(dir string, lines map[string]string) error {
388 path := filepath.Join(dir, indexFile)
389 existing, err := readIndexIn(dir)
390 if err != nil {
391 return err
392 }
393 processed := map[string]bool{}
394 var preserved strings.Builder
395 preservedEmpty := true
396 for line := range strings.SplitSeq(string(existing), "\n") {
397 trimmed := strings.TrimRight(line, "\r")
398 if mt := indexLineRe.FindStringSubmatch(trimmed); mt != nil {
399 name := mt[1]
400 if fresh, ok := lines[name]; ok {
401 preserved.WriteString(fresh)
402 preserved.WriteString("\n")
403 processed[name] = true
404 preservedEmpty = false
405 }
406 continue
407 }
408 preserved.WriteString(trimmed)
409 preserved.WriteString("\n")
410 if strings.TrimSpace(trimmed) != "" {
411 preservedEmpty = false
412 }
413 }
414
415 names := make([]string, 0, len(lines))
416 for n := range lines {
417 if !processed[n] {
418 names = append(names, n)
419 }
420 }
421 sort.Strings(names)
422
423 var b strings.Builder
424 if preservedEmpty && len(names) > 0 {
425 b.WriteString("# Memory\n\n")
426 } else {
427 b.WriteString(preserved.String())
428 }
429 for _, n := range names {
430 b.WriteString(lines[n])
431 b.WriteString("\n")
432 }
433 result := strings.TrimRight(b.String(), "\n")
434 if result != "" {
435 result += "\n"
436 }
437 // The index is derived state, but a torn write would still hide facts
438 // from the next real turn's session-context until the next reindex.
439 return fileutil.AtomicWriteFile(path, []byte(result), 0o644)
440 }
441
442 // reindexIn rewrites the MEMORY.md line for name in the given directory,
443 // preserving every other managed line.
444 func reindexIn(dir, name string, m Memory) error {
445 lines, _, err := indexLinesExceptIn(dir, name)
446 if err != nil {
447 return err
448 }
449 lines[name] = renderIndexLine(name, m)
450 return flushIndexIn(dir, lines)
451 }
452
453 func renderIndexLine(name string, m Memory) string {
454 marker := ""
455 if ResolveActivation(m) == ActivationPinned {
456 marker = " pinned" // the body already rides session-context; no need to read it
457 }
458 return fmt.Sprintf("- [%s](%s.md) — [%s/%s%s] %s",
459 displayTitle(m.Title, name), name,
460 NormalizeFactScope(string(m.Scope)), NormalizeType(string(m.Type)), marker, oneLine(m.Description))
461 }
462
463 // List returns the saved memories parsed from their files, sorted by name. Used
464 // by `/memory` and the desktop memory panel. Reads from both GlobalDir and Dir,
465 // merging results. Files that fail to parse are skipped so one bad file never
466 // hides the rest.
467 func (s Store) List() []Memory {
468 if s.Dir == "" && s.GlobalDir == "" {
469 return nil
470 }
471 var out []Memory
472 seen := map[string]bool{}
473 for _, dir := range s.dirs() {
474 if dir == "" {
475 continue
476 }
477 entries, err := os.ReadDir(dir)
478 if err != nil {
479 continue
480 }
481 for _, e := range entries {
482 if e.IsDir() || e.Name() == indexFile || !strings.HasSuffix(e.Name(), ".md") {
483 continue
484 }
485 if m, ok := loadMemory(filepath.Join(dir, e.Name())); ok {
486 if m.Scope == "" {
487 m.Scope = s.scopeForDir(dir)
488 }
489 if !seen[m.Name] {
490 out = append(out, m)
491 seen[m.Name] = true
492 }
493 }
494 }
495 }
496 sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
497 return out
498 }
499
500 // ListAll returns every active fact from both scopes without the legacy
501 // name-based deduplication performed by List. Callers that understand scope can
502 // use it to resolve project-over-global overrides without hiding either source.
503 func (s Store) ListAll() []Memory {
504 if s.Dir == "" && s.GlobalDir == "" {
505 return nil
506 }
507 var out []Memory
508 for _, dir := range s.dirs() {
509 if dir == "" {
510 continue
511 }
512 entries, err := os.ReadDir(dir)
513 if err != nil {
514 continue
515 }
516 for _, entry := range entries {
517 if entry.IsDir() || entry.Name() == indexFile || !strings.HasSuffix(entry.Name(), ".md") {
518 continue
519 }
520 memory, ok := loadMemory(filepath.Join(dir, entry.Name()))
521 if !ok {
522 continue
523 }
524 if memory.Scope == "" {
525 memory.Scope = s.scopeForDir(dir)
526 }
527 out = append(out, memory)
528 }
529 }
530 sort.Slice(out, func(i, j int) bool {
531 if out[i].Name != out[j].Name {
532 return out[i].Name < out[j].Name
533 }
534 if out[i].Scope != out[j].Scope {
535 return out[i].Scope < out[j].Scope
536 }
537 return out[i].ID < out[j].ID
538 })
539 return out
540 }
541
542 // PinnedGuidanceBudgetChars caps the total pinned-body runes session-context
543 // carries. Guidance that must always hold belongs in REASONIX.md/AGENTS.md
544 // instructions; pinned memory is the bounded middle tier between instructions
545 // and retrieval-only facts, and the cap is enforced at write time so the
546 // snapshot always equals exactly what the user curated.
547 const PinnedGuidanceBudgetChars = 1500
548
549 // pinnedGuidance snapshots explicitly pinned facts (plus legacy global
550 // user/feedback, which ResolveActivation keeps pinned for compatibility) for
551 // session-context, most recently updated first.
552 func (s Store) pinnedGuidance() []Memory {
553 var out []Memory
554 for _, dir := range s.dirs() {
555 if dir == "" {
556 continue
557 }
558 entries, err := os.ReadDir(dir)
559 if err != nil {
560 continue
561 }
562 for _, e := range entries {
563 if e.IsDir() || e.Name() == indexFile || !strings.HasSuffix(e.Name(), ".md") {
564 continue
565 }
566 m, ok := loadMemory(filepath.Join(dir, e.Name()))
567 if !ok {
568 continue
569 }
570 if m.Scope == "" {
571 m.Scope = s.scopeForDir(dir)
572 }
573 if ResolveActivation(m) != ActivationPinned || strings.TrimSpace(m.Body) == "" {
574 continue
575 }
576 out = append(out, m)
577 }
578 }
579 sort.Slice(out, func(i, j int) bool {
580 if !out[i].UpdatedAt.Equal(out[j].UpdatedAt) {
581 return out[i].UpdatedAt.After(out[j].UpdatedAt)
582 }
583 return out[i].Name < out[j].Name
584 })
585 return out
586 }
587
588 // pinnedGuidanceForProject removes pinned guidance shadowed by an equivalent
589 // project fact before the stable session prefix is built. This makes the
590 // documented project-over-global rule deterministic on the first turn instead
591 // of depending on whether automatic recall happens to match the request.
592 func (s Store) pinnedGuidanceForProject() []Memory {
593 guidance := s.pinnedGuidance()
594 if len(guidance) == 0 || s.Dir == "" {
595 return guidance
596 }
597 projectKeys := map[string]bool{}
598 for _, fact := range s.ListAll() {
599 if NormalizeFactScope(string(fact.Scope)) != FactScopeProject {
600 continue
601 }
602 for _, key := range recallIdentityKeys(fact) {
603 if strings.HasSuffix(key, ":") {
604 continue
605 }
606 projectKeys[key] = true
607 }
608 }
609 if len(projectKeys) == 0 {
610 return guidance
611 }
612 out := guidance[:0]
613 for _, fact := range guidance {
614 // Project pinned facts always stay: the shadow rule only suppresses a
615 // GLOBAL fact that an equivalent project fact overrides.
616 shadowed := false
617 if NormalizeFactScope(string(fact.Scope)) == FactScopeGlobal {
618 for _, key := range recallIdentityKeys(fact) {
619 if projectKeys[key] {
620 shadowed = true
621 break
622 }
623 }
624 }
625 if !shadowed {
626 out = append(out, fact)
627 }
628 }
629 return out
630 }
631
632 // ListArchived returns archived memories parsed from .archive/, newest first.
633 // Archived files stay out of List() and the prompt index, so stale facts remain
634 // inspectable without being reused as active truth. Reads from both GlobalDir
635 // and Dir.
636 func (s Store) ListArchived() []ArchivedMemory {
637 if s.Dir == "" && s.GlobalDir == "" {
638 return nil
639 }
640 var out []ArchivedMemory
641 for _, base := range s.dirs() {
642 if base == "" {
643 continue
644 }
645 dir := filepath.Join(base, ".archive")
646 entries, err := os.ReadDir(dir)
647 if err != nil {
648 continue
649 }
650 for _, e := range entries {
651 if e.IsDir() || !strings.HasSuffix(e.Name(), ".md") {
652 continue
653 }
654 path := filepath.Join(dir, e.Name())
655 m, ok := loadMemory(path)
656 if !ok {
657 continue
658 }
659 if m.Scope == "" {
660 m.Scope = s.scopeForDir(base)
661 }
662 when := archiveTimeFromName(e.Name())
663 if when.IsZero() {
664 if info, err := e.Info(); err == nil {
665 when = info.ModTime()
666 }
667 }
668 out = append(out, ArchivedMemory{Memory: m, Path: path, ArchivedAt: when})
669 }
670 }
671 sort.Slice(out, func(i, j int) bool {
672 if !out[i].ArchivedAt.Equal(out[j].ArchivedAt) {
673 return out[i].ArchivedAt.After(out[j].ArchivedAt)
674 }
675 if out[i].Name != out[j].Name {
676 return out[i].Name < out[j].Name
677 }
678 return out[i].Path < out[j].Path
679 })
680 return out
681 }
682
683 func archiveTimeFromName(name string) time.Time {
684 const stampLen = len("20060102-150405.000")
685 if len(name) <= stampLen || name[stampLen] != '-' {
686 return time.Time{}
687 }
688 when, err := time.ParseInLocation("20060102-150405.000", name[:stampLen], time.UTC)
689 if err != nil {
690 return time.Time{}
691 }
692 return when
693 }
694
695 // loadMemory parses one fact file back into a Memory. It tolerates the minimal
696 // frontmatter render writes; a file without frontmatter still loads with its
697 // body and a name derived from the filename.
698 func loadMemory(path string) (Memory, bool) {
699 b, err := fileencoding.ReadFileUTF8(path)
700 if err != nil {
701 return Memory{}, false
702 }
703 fm, body := splitFrontmatter(string(b))
704 m := Memory{
705 ID: fm["id"],
706 Revision: parsePositiveInt(fm["revision"]),
707 CreatedAt: parseMemoryTime(fm["created_at"]),
708 UpdatedAt: parseMemoryTime(fm["updated_at"]),
709 Name: fm["name"],
710 Title: fm["title"],
711 Description: fm["description"],
712 Keywords: fm["keywords"],
713 Activation: NormalizeActivation(fm["activation"]),
714 Volatility: NormalizeVolatility(fm["volatility"]),
715 SubjectKey: NormalizeSubjectKey(fm["subject_key"]),
716 ExpiresAt: parseMemoryTime(fm["expires_at"]),
717 LastVerifiedAt: parseMemoryTime(fm["last_verified_at"]),
718 Type: persistedFactType(fm),
719 Scope: factScopeFromFrontmatter(fm["scope"]),
720 Body: strings.TrimSpace(body),
721 }
722 if m.Name == "" {
723 m.Name = strings.TrimSuffix(filepath.Base(path), ".md")
724 }
725 if m.ID == "" {
726 m.ID = legacyMemoryID(m.Name, legacyIdentityScope(m))
727 }
728 if m.Revision <= 0 {
729 m.Revision = 1
730 }
731 if info, err := os.Stat(path); err == nil {
732 if m.CreatedAt.IsZero() {
733 m.CreatedAt = info.ModTime().UTC()
734 }
735 if m.UpdatedAt.IsZero() {
736 m.UpdatedAt = info.ModTime().UTC()
737 }
738 }
739 return m, true
740 }
741
742 func legacyIdentityScope(m Memory) FactScope {
743 if m.Scope != "" {
744 return NormalizeFactScope(string(m.Scope))
745 }
746 if m.Type == TypeUser || m.Type == TypeFeedback {
747 return FactScopeGlobal
748 }
749 return FactScopeProject
750 }
751
752 func parsePositiveInt(value string) int {
753 n, err := strconv.Atoi(strings.TrimSpace(value))
754 if err != nil || n < 1 {
755 return 0
756 }
757 return n
758 }
759
760 func parseMemoryTime(value string) time.Time {
761 when, _ := time.Parse(time.RFC3339Nano, strings.TrimSpace(value))
762 return when
763 }
764
765 func persistedFactType(fm map[string]string) Type {
766 if t := Type(strings.ToLower(strings.TrimSpace(fm["fact_type"]))); validTypes[t] {
767 return t
768 }
769 return NormalizeType(fm["type"])
770 }
771
772 func factScopeFromFrontmatter(s string) FactScope {
773 switch FactScope(strings.ToLower(strings.TrimSpace(s))) {
774 case FactScopeProject:
775 return FactScopeProject
776 case FactScopeGlobal:
777 return FactScopeGlobal
778 default:
779 return ""
780 }
781 }
782
783 func (s Store) scopeForDir(dir string) FactScope {
784 if s.GlobalDir != "" && sameDir(dir, s.GlobalDir) {
785 return FactScopeGlobal
786 }
787 return FactScopeProject
788 }
789
790 func (s Store) scopeForPath(path string) FactScope {
791 return s.scopeForDir(filepath.Dir(path))
792 }
793
794 // splitFrontmatter is a thin wrapper; the real parser lives in
795 // internal/frontmatter.
796 func splitFrontmatter(s string) (map[string]string, string) {
797 return frontmatter.Split(s)
798 }
799
800 // slugRe strips everything but Unicode letters and digits.
801 var slugRe = regexp.MustCompile(`[^\p{L}\p{N}]+`)
802
803 // slug normalises a name into a kebab-case, filesystem-safe stem. The stem is
804 // bounded so `<stem>.md` stays under the 255-byte filename component limit —
805 // a name distilled from a long title/description previously failed the write
806 // with ENAMETOOLONG. Names short enough to have ever been written are
807 // returned unchanged, so existing files keep resolving.
808 func slug(s string) string {
809 stem := strings.Trim(slugRe.ReplaceAllString(strings.ToLower(strings.TrimSpace(s)), "-"), "-")
810 return config.BoundFilenameComponent(stem, 255-len(".md"))
811 }
812
813 // oneLine collapses whitespace so a description can't break the single-line
814 // index or frontmatter format.
815 func oneLine(s string) string {
816 return strings.Join(strings.Fields(s), " ")
817 }
818
819 // displayTitle is the index link label: the given title, or a de-kebabed name
820 // when none was supplied, so a bare slug never leaks into the index.
821 func displayTitle(title, name string) string {
822 if t := oneLine(title); t != "" {
823 return t
824 }
825 return strings.ReplaceAll(name, "-", " ")
826 }
827
827 lines GO