opencode-claude-memory 1.5.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -1
- package/bin/opencode-memory +435 -12
- package/package.json +1 -1
- package/src/index.ts +165 -16
- package/src/memory.ts +44 -15
- package/src/memoryScan.ts +130 -0
- package/src/paths.ts +6 -3
- package/src/prompt.ts +187 -112
- package/src/recall.ts +81 -44
package/src/prompt.ts
CHANGED
|
@@ -1,97 +1,179 @@
|
|
|
1
1
|
import { MEMORY_TYPES } from "./memory.js"
|
|
2
2
|
import { readIndex, truncateEntrypoint } from "./memory.js"
|
|
3
|
-
import { getMemoryDir, ENTRYPOINT_NAME } from "./paths.js"
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
user
|
|
27
|
-
|
|
28
|
-
</
|
|
29
|
-
|
|
30
|
-
<
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
</
|
|
40
|
-
|
|
41
|
-
<
|
|
42
|
-
<
|
|
43
|
-
<
|
|
44
|
-
<
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
user:
|
|
49
|
-
assistant: [saves
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
<
|
|
57
|
-
<
|
|
58
|
-
user
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
"
|
|
3
|
+
import { getMemoryDir, ENTRYPOINT_NAME, MAX_ENTRYPOINT_LINES, getProjectDir } from "./paths.js"
|
|
4
|
+
|
|
5
|
+
// Port of Claude Code's MEMORY_FRONTMATTER_EXAMPLE from memoryTypes.ts
|
|
6
|
+
const FRONTMATTER_EXAMPLE = [
|
|
7
|
+
"```markdown",
|
|
8
|
+
"---",
|
|
9
|
+
"name: {{memory name}}",
|
|
10
|
+
"description: {{one-line description — used to decide relevance in future conversations, so be specific}}",
|
|
11
|
+
`type: {{${MEMORY_TYPES.join(", ")}}}`,
|
|
12
|
+
"---",
|
|
13
|
+
"",
|
|
14
|
+
"{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}",
|
|
15
|
+
"```",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
// Port of Claude Code's TYPES_SECTION_INDIVIDUAL from memoryTypes.ts
|
|
19
|
+
const TYPES_SECTION = [
|
|
20
|
+
"## Types of memory",
|
|
21
|
+
"",
|
|
22
|
+
"There are several discrete types of memory that you can store in your memory system:",
|
|
23
|
+
"",
|
|
24
|
+
"<types>",
|
|
25
|
+
"<type>",
|
|
26
|
+
" <name>user</name>",
|
|
27
|
+
" <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>",
|
|
28
|
+
" <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>",
|
|
29
|
+
" <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>",
|
|
30
|
+
" <examples>",
|
|
31
|
+
" user: I'm a data scientist investigating what logging we have in place",
|
|
32
|
+
" assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]",
|
|
33
|
+
"",
|
|
34
|
+
" user: I've been writing Go for ten years but this is my first time touching the React side of this repo",
|
|
35
|
+
" assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]",
|
|
36
|
+
" </examples>",
|
|
37
|
+
"</type>",
|
|
38
|
+
"<type>",
|
|
39
|
+
" <name>feedback</name>",
|
|
40
|
+
" <description>Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>",
|
|
41
|
+
" <when_to_save>Any time the user corrects your approach (\"no not that\", \"don't\", \"stop doing X\") OR confirms a non-obvious approach worked (\"yes exactly\", \"perfect, keep doing that\", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>",
|
|
42
|
+
" <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>",
|
|
43
|
+
" <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>",
|
|
44
|
+
" <examples>",
|
|
45
|
+
" user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed",
|
|
46
|
+
" assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]",
|
|
47
|
+
"",
|
|
48
|
+
" user: stop summarizing what you just did at the end of every response, I can read the diff",
|
|
49
|
+
" assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]",
|
|
50
|
+
"",
|
|
51
|
+
" user: yeah the single bundled PR was the right call here, splitting this one would've just been churn",
|
|
52
|
+
" assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach — a validated judgment call, not a correction]",
|
|
53
|
+
" </examples>",
|
|
54
|
+
"</type>",
|
|
55
|
+
"<type>",
|
|
56
|
+
" <name>project</name>",
|
|
57
|
+
" <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>",
|
|
58
|
+
" <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., \"Thursday\" → \"2026-03-05\"), so the memory remains interpretable after time passes.</when_to_save>",
|
|
59
|
+
" <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>",
|
|
60
|
+
" <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>",
|
|
61
|
+
" <examples>",
|
|
62
|
+
" user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch",
|
|
63
|
+
" assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]",
|
|
64
|
+
"",
|
|
65
|
+
" user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements",
|
|
66
|
+
" assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics]",
|
|
67
|
+
" </examples>",
|
|
68
|
+
"</type>",
|
|
69
|
+
"<type>",
|
|
70
|
+
" <name>reference</name>",
|
|
71
|
+
" <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>",
|
|
72
|
+
" <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>",
|
|
73
|
+
" <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>",
|
|
74
|
+
" <examples>",
|
|
75
|
+
` user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs`,
|
|
76
|
+
` assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]`,
|
|
77
|
+
"",
|
|
78
|
+
" user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone",
|
|
79
|
+
" assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]",
|
|
80
|
+
" </examples>",
|
|
81
|
+
"</type>",
|
|
82
|
+
"</types>",
|
|
83
|
+
"",
|
|
84
|
+
].join("\n")
|
|
85
|
+
|
|
86
|
+
// Port of Claude Code's WHAT_NOT_TO_SAVE_SECTION from memoryTypes.ts
|
|
87
|
+
const WHAT_NOT_TO_SAVE = [
|
|
88
|
+
"## What NOT to save in memory",
|
|
89
|
+
"",
|
|
90
|
+
"- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.",
|
|
91
|
+
"- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.",
|
|
92
|
+
"- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.",
|
|
93
|
+
"- Anything already documented in AGENTS.md or project config files.",
|
|
94
|
+
"- Ephemeral task details: in-progress work, temporary state, current conversation context.",
|
|
95
|
+
"",
|
|
96
|
+
"These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.",
|
|
97
|
+
].join("\n")
|
|
98
|
+
|
|
99
|
+
// Port of Claude Code's WHEN_TO_ACCESS_SECTION from memoryTypes.ts
|
|
100
|
+
const WHEN_TO_ACCESS = [
|
|
101
|
+
"## When to access memories",
|
|
102
|
+
"- When memories seem relevant, or the user references prior-conversation work.",
|
|
103
|
+
"- You MUST access memory when the user explicitly asks you to check, recall, or remember.",
|
|
104
|
+
"- If the user says to *ignore* or *not use* memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.",
|
|
105
|
+
"- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.",
|
|
106
|
+
].join("\n")
|
|
107
|
+
|
|
108
|
+
// Port of Claude Code's TRUSTING_RECALL_SECTION from memoryTypes.ts
|
|
109
|
+
const TRUSTING_RECALL = [
|
|
110
|
+
"## Before recommending from memory",
|
|
111
|
+
"",
|
|
112
|
+
"A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:",
|
|
113
|
+
"",
|
|
114
|
+
"- If the memory names a file path: check the file exists.",
|
|
115
|
+
"- If the memory names a function or flag: grep for it.",
|
|
116
|
+
"- If the user is about to act on your recommendation (not just asking about history), verify first.",
|
|
117
|
+
"",
|
|
118
|
+
'"The memory says X exists" is not the same as "X exists now."',
|
|
119
|
+
"",
|
|
120
|
+
"A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot.",
|
|
121
|
+
].join("\n")
|
|
122
|
+
|
|
123
|
+
// Port of Claude Code's buildSearchingPastContextSection() from memdir.ts.
|
|
124
|
+
// Guides the model to grep memory files and session transcripts when
|
|
125
|
+
// looking for past context, rather than guessing or hallucinating.
|
|
126
|
+
function buildSearchingPastContextSection(memoryDir: string, projectDir: string): string[] {
|
|
127
|
+
const memSearch = `grep -rn "<search term>" ${memoryDir} --include="*.md"`
|
|
128
|
+
const transcriptSearch = `grep -rn "<search term>" ${projectDir}/ --include="*.jsonl"`
|
|
129
|
+
return [
|
|
130
|
+
"## Searching past context",
|
|
131
|
+
"",
|
|
132
|
+
"When looking for past context:",
|
|
133
|
+
"1. Search topic files in your memory directory:",
|
|
134
|
+
"```",
|
|
135
|
+
memSearch,
|
|
136
|
+
"```",
|
|
137
|
+
"2. Session transcript logs (last resort — large files, slow):",
|
|
138
|
+
"```",
|
|
139
|
+
transcriptSearch,
|
|
140
|
+
"```",
|
|
141
|
+
"Use narrow search terms (error messages, file paths, function names) rather than broad keywords.",
|
|
142
|
+
"",
|
|
143
|
+
]
|
|
144
|
+
}
|
|
89
145
|
|
|
90
|
-
|
|
146
|
+
export type BuildMemorySystemPromptOptions = {
|
|
147
|
+
includeIndex?: boolean
|
|
148
|
+
}
|
|
91
149
|
|
|
92
|
-
export function buildMemorySystemPrompt(
|
|
150
|
+
export function buildMemorySystemPrompt(
|
|
151
|
+
worktree: string,
|
|
152
|
+
recalledMemoriesSection?: string,
|
|
153
|
+
options: BuildMemorySystemPromptOptions = {},
|
|
154
|
+
): string {
|
|
93
155
|
const memoryDir = getMemoryDir(worktree)
|
|
156
|
+
const projectDir = getProjectDir(worktree)
|
|
94
157
|
const indexContent = readIndex(worktree)
|
|
158
|
+
const includeIndex = options.includeIndex ?? true
|
|
159
|
+
|
|
160
|
+
const howToSave = [
|
|
161
|
+
"## How to save memories",
|
|
162
|
+
"",
|
|
163
|
+
"Saving a memory is a two-step process:",
|
|
164
|
+
"",
|
|
165
|
+
'**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:',
|
|
166
|
+
"",
|
|
167
|
+
...FRONTMATTER_EXAMPLE,
|
|
168
|
+
"",
|
|
169
|
+
`**Step 2** — add a pointer to that file in \`${ENTRYPOINT_NAME}\`. \`${ENTRYPOINT_NAME}\` is an index, not a memory — each entry should be one line, under ~150 characters: \`- [Title](file.md) — one-line hook\`. It has no frontmatter. Never write memory content directly into \`${ENTRYPOINT_NAME}\`.`,
|
|
170
|
+
"",
|
|
171
|
+
`- \`${ENTRYPOINT_NAME}\` is always loaded into your conversation context — lines after ${MAX_ENTRYPOINT_LINES} will be truncated, so keep the index concise`,
|
|
172
|
+
"- Keep the name, description, and type fields in memory files up-to-date with the content",
|
|
173
|
+
"- Organize memory semantically by topic, not chronologically",
|
|
174
|
+
"- Update or remove memories that turn out to be wrong or outdated",
|
|
175
|
+
"- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.",
|
|
176
|
+
].join("\n")
|
|
95
177
|
|
|
96
178
|
const lines: string[] = [
|
|
97
179
|
"# Auto Memory",
|
|
@@ -100,43 +182,36 @@ export function buildMemorySystemPrompt(worktree: string, recalledMemoriesSectio
|
|
|
100
182
|
"",
|
|
101
183
|
"You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.",
|
|
102
184
|
"",
|
|
103
|
-
"If the user explicitly asks you to remember something, save it immediately
|
|
185
|
+
"If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.",
|
|
104
186
|
"",
|
|
105
187
|
TYPES_SECTION,
|
|
106
|
-
"",
|
|
107
188
|
WHAT_NOT_TO_SAVE,
|
|
108
189
|
"",
|
|
109
|
-
|
|
110
|
-
"",
|
|
111
|
-
"Use the `memory_save` tool to create or update a memory. Each memory goes in its own file with frontmatter:",
|
|
112
|
-
"",
|
|
113
|
-
FRONTMATTER_EXAMPLE,
|
|
114
|
-
"",
|
|
115
|
-
`- The \`${ENTRYPOINT_NAME}\` index is managed automatically — you don't need to edit it`,
|
|
116
|
-
"- Organize memory semantically by topic, not chronologically",
|
|
117
|
-
"- Update or remove memories that turn out to be wrong or outdated",
|
|
118
|
-
"- Do not write duplicate memories. First use `memory_list` or `memory_search` to check if there is an existing memory you can update before writing a new one.",
|
|
190
|
+
howToSave,
|
|
119
191
|
"",
|
|
120
192
|
WHEN_TO_ACCESS,
|
|
121
193
|
"",
|
|
122
194
|
TRUSTING_RECALL,
|
|
123
195
|
"",
|
|
124
196
|
"## Memory and other forms of persistence",
|
|
125
|
-
"Memory is one of several persistence mechanisms. The distinction is that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.",
|
|
126
|
-
"- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task
|
|
127
|
-
"- When to use or update tasks instead of memory: When you need to break your work into discrete steps or track progress
|
|
197
|
+
"Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.",
|
|
198
|
+
"- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.",
|
|
199
|
+
"- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.",
|
|
128
200
|
"",
|
|
201
|
+
...buildSearchingPastContextSection(memoryDir, projectDir),
|
|
129
202
|
]
|
|
130
203
|
|
|
131
|
-
if (
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
204
|
+
if (includeIndex) {
|
|
205
|
+
if (indexContent.trim()) {
|
|
206
|
+
const { content: truncated } = truncateEntrypoint(indexContent)
|
|
207
|
+
lines.push(`## ${ENTRYPOINT_NAME}`, "", truncated)
|
|
208
|
+
} else {
|
|
209
|
+
lines.push(
|
|
210
|
+
`## ${ENTRYPOINT_NAME}`,
|
|
211
|
+
"",
|
|
212
|
+
`Your ${ENTRYPOINT_NAME} is currently empty. When you save new memories, they will appear here.`,
|
|
213
|
+
)
|
|
214
|
+
}
|
|
140
215
|
}
|
|
141
216
|
|
|
142
217
|
if (recalledMemoriesSection?.trim()) {
|
package/src/recall.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
const encoder = new TextEncoder()
|
|
1
|
+
import { readFileSync } from "fs"
|
|
2
|
+
import { scanMemoryFiles, type MemoryHeader } from "./memoryScan.js"
|
|
3
|
+
import { getMemoryDir } from "./paths.js"
|
|
5
4
|
|
|
6
5
|
export type RecalledMemory = {
|
|
7
6
|
fileName: string
|
|
7
|
+
filePath: string
|
|
8
8
|
name: string
|
|
9
9
|
type: string
|
|
10
10
|
description: string
|
|
@@ -16,24 +16,46 @@ const MAX_RECALLED_MEMORIES = 5
|
|
|
16
16
|
const MAX_MEMORY_LINES = 200
|
|
17
17
|
const MAX_MEMORY_BYTES = 4096
|
|
18
18
|
|
|
19
|
+
const encoder = new TextEncoder()
|
|
20
|
+
|
|
19
21
|
function tokenizeQuery(query: string): string[] {
|
|
20
22
|
return [...new Set(query.toLowerCase().split(/\s+/).map((token) => token.trim()).filter((token) => token.length >= 2))]
|
|
21
23
|
}
|
|
22
24
|
|
|
23
|
-
function
|
|
25
|
+
function readMemoryContent(filePath: string): string {
|
|
24
26
|
try {
|
|
25
|
-
|
|
27
|
+
const raw = readFileSync(filePath, "utf-8")
|
|
28
|
+
const trimmed = raw.trim()
|
|
29
|
+
if (!trimmed.startsWith("---")) return trimmed
|
|
30
|
+
|
|
31
|
+
const lines = trimmed.split("\n")
|
|
32
|
+
let closingIdx = -1
|
|
33
|
+
for (let i = 1; i < lines.length; i++) {
|
|
34
|
+
if (lines[i].trimEnd() === "---") {
|
|
35
|
+
closingIdx = i
|
|
36
|
+
break
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return closingIdx === -1 ? trimmed : lines.slice(closingIdx + 1).join("\n").trim()
|
|
26
40
|
} catch {
|
|
27
|
-
return
|
|
41
|
+
return ""
|
|
28
42
|
}
|
|
29
43
|
}
|
|
30
44
|
|
|
31
|
-
function
|
|
45
|
+
function scoreHeader(header: MemoryHeader, content: string, terms: string[]): number {
|
|
32
46
|
if (terms.length === 0) return 0
|
|
33
|
-
|
|
47
|
+
|
|
48
|
+
const nameHaystack = (header.name ?? "").toLowerCase()
|
|
49
|
+
const descHaystack = (header.description ?? "").toLowerCase()
|
|
50
|
+
const filenameHaystack = header.filename.toLowerCase()
|
|
51
|
+
const contentHaystack = content.toLowerCase()
|
|
52
|
+
|
|
34
53
|
let score = 0
|
|
35
54
|
for (const term of terms) {
|
|
36
|
-
if (
|
|
55
|
+
if (nameHaystack.includes(term)) score += 3
|
|
56
|
+
if (descHaystack.includes(term)) score += 3
|
|
57
|
+
if (filenameHaystack.includes(term)) score += 1
|
|
58
|
+
if (contentHaystack.includes(term)) score += 1
|
|
37
59
|
}
|
|
38
60
|
return score
|
|
39
61
|
}
|
|
@@ -60,53 +82,68 @@ function truncateMemoryContent(content: string): string {
|
|
|
60
82
|
return kept.join("\n")
|
|
61
83
|
}
|
|
62
84
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
85
|
+
// Port of Claude Code's findRelevantMemories pattern, adapted for
|
|
86
|
+
// keyword-based selection (no LLM side query available in plugin context).
|
|
87
|
+
function isToolReferenceMemory(header: MemoryHeader, content: string, recentTools: readonly string[]): boolean {
|
|
88
|
+
if (recentTools.length === 0) return false
|
|
89
|
+
const type = header.type
|
|
90
|
+
if (type !== "reference") return false
|
|
66
91
|
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
return {
|
|
71
|
-
entry,
|
|
72
|
-
mtimeMs,
|
|
73
|
-
}
|
|
74
|
-
})
|
|
92
|
+
const haystack = `${header.name ?? ""}\n${header.description ?? ""}\n${content}`.toLowerCase()
|
|
93
|
+
const warningSignals = ["warning", "gotcha", "issue", "bug", "caveat", "pitfall", "known issue"]
|
|
94
|
+
if (warningSignals.some((w) => haystack.includes(w))) return false
|
|
75
95
|
|
|
76
|
-
const
|
|
96
|
+
const toolHaystack = recentTools.map((t) => t.toLowerCase())
|
|
97
|
+
return toolHaystack.some((tool) => haystack.includes(tool))
|
|
98
|
+
}
|
|
77
99
|
|
|
78
|
-
|
|
100
|
+
export function recallRelevantMemories(
|
|
101
|
+
worktree: string,
|
|
102
|
+
query?: string,
|
|
103
|
+
alreadySurfaced: ReadonlySet<string> = new Set(),
|
|
104
|
+
recentTools: readonly string[] = [],
|
|
105
|
+
): RecalledMemory[] {
|
|
106
|
+
const memoryDir = getMemoryDir(worktree)
|
|
107
|
+
const headers = scanMemoryFiles(memoryDir).filter(
|
|
108
|
+
(h) => !alreadySurfaced.has(`${h.name ?? h.filename.replace(/\.md$/, "").replace(/.*\//, "")}|${h.type ?? "user"}`),
|
|
109
|
+
)
|
|
110
|
+
if (headers.length === 0) return []
|
|
79
111
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
.map((item) => ({
|
|
83
|
-
...item,
|
|
84
|
-
score: scoreMemory(item.entry, terms),
|
|
85
|
-
}))
|
|
86
|
-
.sort((a, b) => b.score - a.score || b.mtimeMs - a.mtimeMs)
|
|
112
|
+
const now = Date.now()
|
|
113
|
+
const terms = query ? tokenizeQuery(query) : []
|
|
87
114
|
|
|
88
|
-
|
|
89
|
-
|
|
115
|
+
const scored = headers.map((header) => {
|
|
116
|
+
const content = readMemoryContent(header.filePath)
|
|
117
|
+
return {
|
|
118
|
+
header,
|
|
119
|
+
content,
|
|
120
|
+
score: scoreHeader(header, content, terms),
|
|
90
121
|
}
|
|
91
|
-
}
|
|
122
|
+
}).filter(({ header, content }) => !isToolReferenceMemory(header, content, recentTools))
|
|
92
123
|
|
|
93
|
-
if (
|
|
94
|
-
|
|
124
|
+
if (terms.length > 0 && scored.some((s) => s.score > 0)) {
|
|
125
|
+
scored.sort((a, b) => b.score - a.score || b.header.mtimeMs - a.header.mtimeMs)
|
|
126
|
+
} else {
|
|
127
|
+
scored.sort((a, b) => b.header.mtimeMs - a.header.mtimeMs)
|
|
95
128
|
}
|
|
96
129
|
|
|
97
|
-
return
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
130
|
+
return scored.slice(0, MAX_RECALLED_MEMORIES).map(({ header, content }) => {
|
|
131
|
+
const nameFromFilename = header.filename.replace(/\.md$/, "").replace(/.*\//, "")
|
|
132
|
+
return {
|
|
133
|
+
fileName: header.filename,
|
|
134
|
+
filePath: header.filePath,
|
|
135
|
+
name: header.name ?? nameFromFilename,
|
|
136
|
+
type: header.type ?? "user",
|
|
137
|
+
description: header.description ?? "",
|
|
138
|
+
content: truncateMemoryContent(content),
|
|
139
|
+
ageInDays: Math.max(0, Math.floor((now - header.mtimeMs) / (1000 * 60 * 60 * 24))),
|
|
140
|
+
}
|
|
141
|
+
})
|
|
105
142
|
}
|
|
106
143
|
|
|
107
144
|
function formatAgeWarning(ageInDays: number): string {
|
|
108
145
|
if (ageInDays <= 1) return ""
|
|
109
|
-
return `\n>
|
|
146
|
+
return `\n> This memory is ${ageInDays} days old. Memories are point-in-time observations, not live state — claims about code behavior or file:line citations may be outdated. Verify against current code before asserting as fact.\n`
|
|
110
147
|
}
|
|
111
148
|
|
|
112
149
|
export function formatRecalledMemories(memories: RecalledMemory[]): string {
|