opencode-claude-memory 1.6.0 → 1.6.2

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.
@@ -0,0 +1,106 @@
1
+ import { readdirSync, readFileSync, statSync } from "fs";
2
+ import { basename, join } from "path";
3
+ import { getMemoryDir, ENTRYPOINT_NAME, MAX_MEMORY_FILES, FRONTMATTER_MAX_LINES, } from "./paths.js";
4
+ const MEMORY_TYPES = ["user", "feedback", "project", "reference"];
5
+ function parseMemoryType(raw) {
6
+ if (!raw)
7
+ return undefined;
8
+ return MEMORY_TYPES.includes(raw) ? raw : undefined;
9
+ }
10
+ function readFileHeader(filePath, maxLines) {
11
+ try {
12
+ const raw = readFileSync(filePath, "utf-8");
13
+ const stat = statSync(filePath);
14
+ const lines = raw.split("\n");
15
+ const header = lines.slice(0, maxLines).join("\n");
16
+ return { content: header, mtimeMs: stat.mtimeMs };
17
+ }
18
+ catch {
19
+ return { content: "", mtimeMs: 0 };
20
+ }
21
+ }
22
+ function parseFrontmatterHeader(raw) {
23
+ const trimmed = raw.trim();
24
+ if (!trimmed.startsWith("---")) {
25
+ return {};
26
+ }
27
+ const lines = trimmed.split("\n");
28
+ let closingLineIdx = -1;
29
+ for (let i = 1; i < lines.length; i++) {
30
+ if (lines[i].trimEnd() === "---") {
31
+ closingLineIdx = i;
32
+ break;
33
+ }
34
+ }
35
+ if (closingLineIdx === -1) {
36
+ return {};
37
+ }
38
+ const frontmatter = {};
39
+ for (let i = 1; i < closingLineIdx; i++) {
40
+ const line = lines[i];
41
+ const colonIdx = line.indexOf(":");
42
+ if (colonIdx === -1)
43
+ continue;
44
+ const key = line.slice(0, colonIdx).trim();
45
+ const value = line.slice(colonIdx + 1).trim();
46
+ if (key && value) {
47
+ frontmatter[key] = value;
48
+ }
49
+ }
50
+ return frontmatter;
51
+ }
52
+ /**
53
+ * Recursive scan of memory directory. Reads only frontmatter (first N lines),
54
+ * returns headers sorted by mtime desc, capped at MAX_MEMORY_FILES.
55
+ * Port of Claude Code's scanMemoryFiles().
56
+ */
57
+ export function scanMemoryFiles(memoryDir) {
58
+ try {
59
+ const entries = readdirSync(memoryDir, { recursive: true, encoding: "utf-8" });
60
+ const mdFiles = entries.filter((f) => f.endsWith(".md") && basename(f) !== ENTRYPOINT_NAME);
61
+ const headers = [];
62
+ for (const relativePath of mdFiles) {
63
+ const filePath = join(memoryDir, relativePath);
64
+ try {
65
+ const { content, mtimeMs } = readFileHeader(filePath, FRONTMATTER_MAX_LINES);
66
+ const frontmatter = parseFrontmatterHeader(content);
67
+ headers.push({
68
+ filename: relativePath,
69
+ filePath,
70
+ mtimeMs,
71
+ name: frontmatter.name || null,
72
+ description: frontmatter.description || null,
73
+ type: parseMemoryType(frontmatter.type),
74
+ });
75
+ }
76
+ catch {
77
+ // skip unreadable files
78
+ }
79
+ }
80
+ return headers
81
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
82
+ .slice(0, MAX_MEMORY_FILES);
83
+ }
84
+ catch {
85
+ return [];
86
+ }
87
+ }
88
+ // Port of Claude Code's formatMemoryManifest():
89
+ // `- [type] filename (ISO timestamp): description` per line
90
+ export function formatMemoryManifest(memories) {
91
+ return memories
92
+ .map((m) => {
93
+ const tag = m.type ? `[${m.type}] ` : "";
94
+ const ts = new Date(m.mtimeMs).toISOString();
95
+ return m.description
96
+ ? `- ${tag}${m.filename} (${ts}): ${m.description}`
97
+ : `- ${tag}${m.filename} (${ts})`;
98
+ })
99
+ .join("\n");
100
+ }
101
+ export function getMemoryManifest(worktree) {
102
+ const memoryDir = getMemoryDir(worktree);
103
+ const headers = scanMemoryFiles(memoryDir);
104
+ const manifest = formatMemoryManifest(headers);
105
+ return { headers, manifest };
106
+ }
@@ -0,0 +1,14 @@
1
+ export declare const ENTRYPOINT_NAME = "MEMORY.md";
2
+ export declare const MAX_ENTRYPOINT_LINES = 200;
3
+ export declare const MAX_ENTRYPOINT_BYTES = 25000;
4
+ export declare const MAX_MEMORY_FILES = 200;
5
+ export declare const MAX_MEMORY_FILE_BYTES = 40000;
6
+ export declare const FRONTMATTER_MAX_LINES = 30;
7
+ export declare function validateMemoryFileName(fileName: string): string;
8
+ export declare function sanitizePath(name: string): string;
9
+ export declare function findCanonicalGitRoot(startPath: string): string | null;
10
+ export declare function getProjectDir(worktree: string): string;
11
+ export declare function getMemoryDir(worktree: string): string;
12
+ export declare function getMemoryEntrypoint(worktree: string): string;
13
+ export declare function isMemoryPath(absolutePath: string, worktree: string): boolean;
14
+ export declare function ensureDir(dir: string): void;
package/dist/paths.js ADDED
@@ -0,0 +1,141 @@
1
+ // Claude Code compatible memory directory path resolution.
2
+ // Directory: ~/.claude/projects/<sanitizePath(canonicalGitRoot)>/memory/
3
+ // Ensures bidirectional memory sharing between Claude Code and OpenCode.
4
+ import { homedir } from "os";
5
+ import { join, dirname, resolve, sep } from "path";
6
+ import { mkdirSync, existsSync, readFileSync, statSync, realpathSync } from "fs";
7
+ export const ENTRYPOINT_NAME = "MEMORY.md";
8
+ export const MAX_ENTRYPOINT_LINES = 200;
9
+ export const MAX_ENTRYPOINT_BYTES = 25_000;
10
+ export const MAX_MEMORY_FILES = 200;
11
+ export const MAX_MEMORY_FILE_BYTES = 40_000;
12
+ export const FRONTMATTER_MAX_LINES = 30;
13
+ export function validateMemoryFileName(fileName) {
14
+ const base = fileName.endsWith(".md") ? fileName.slice(0, -3) : fileName;
15
+ if (base.length === 0) {
16
+ throw new Error("Memory file name cannot be empty");
17
+ }
18
+ if (base.includes("/") || base.includes("\\")) {
19
+ throw new Error(`Memory file name must not contain path separators: ${fileName}`);
20
+ }
21
+ if (base.includes("..")) {
22
+ throw new Error(`Memory file name must not contain path traversal: ${fileName}`);
23
+ }
24
+ if (base.includes("\0")) {
25
+ throw new Error(`Memory file name must not contain null bytes: ${fileName}`);
26
+ }
27
+ if (base.startsWith(".")) {
28
+ throw new Error(`Memory file name must not start with '.': ${fileName}`);
29
+ }
30
+ if (base.toUpperCase() === "MEMORY") {
31
+ throw new Error(`'MEMORY' is a reserved name and cannot be used as a memory file name`);
32
+ }
33
+ return `${base}.md`;
34
+ }
35
+ const MAX_SANITIZED_LENGTH = 200;
36
+ // Exact copy of Claude Code's djb2Hash() from utils/hash.ts
37
+ function djb2Hash(str) {
38
+ let hash = 0;
39
+ for (let i = 0; i < str.length; i++) {
40
+ hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0;
41
+ }
42
+ return hash;
43
+ }
44
+ function simpleHash(str) {
45
+ return Math.abs(djb2Hash(str)).toString(36);
46
+ }
47
+ // Exact copy of Claude Code's sanitizePath() from utils/sessionStoragePortable.ts
48
+ export function sanitizePath(name) {
49
+ const sanitized = name.replace(/[^a-zA-Z0-9]/g, "-");
50
+ if (sanitized.length <= MAX_SANITIZED_LENGTH) {
51
+ return sanitized;
52
+ }
53
+ const hash = simpleHash(name);
54
+ return `${sanitized.slice(0, MAX_SANITIZED_LENGTH)}-${hash}`;
55
+ }
56
+ // Matches Claude Code's findGitRoot() from utils/git.ts
57
+ function findGitRoot(startPath) {
58
+ let current = resolve(startPath);
59
+ const root = current.substring(0, current.indexOf(sep) + 1) || sep;
60
+ while (current !== root) {
61
+ try {
62
+ const gitPath = join(current, ".git");
63
+ const s = statSync(gitPath);
64
+ if (s.isDirectory() || s.isFile()) {
65
+ return current.normalize("NFC");
66
+ }
67
+ }
68
+ catch { }
69
+ const parent = dirname(current);
70
+ if (parent === current)
71
+ break;
72
+ current = parent;
73
+ }
74
+ try {
75
+ const gitPath = join(root, ".git");
76
+ const s = statSync(gitPath);
77
+ if (s.isDirectory() || s.isFile()) {
78
+ return root.normalize("NFC");
79
+ }
80
+ }
81
+ catch { }
82
+ return null;
83
+ }
84
+ // Matches Claude Code's resolveCanonicalRoot() from utils/git.ts
85
+ // Resolves worktrees to the main repo root via .git -> gitdir -> commondir chain
86
+ function resolveCanonicalRoot(gitRoot) {
87
+ try {
88
+ const gitContent = readFileSync(join(gitRoot, ".git"), "utf-8").trim();
89
+ if (!gitContent.startsWith("gitdir:")) {
90
+ return gitRoot;
91
+ }
92
+ const worktreeGitDir = resolve(gitRoot, gitContent.slice("gitdir:".length).trim());
93
+ const commonDir = resolve(worktreeGitDir, readFileSync(join(worktreeGitDir, "commondir"), "utf-8").trim());
94
+ // SECURITY: validate worktreeGitDir is a direct child of <commonDir>/worktrees/
95
+ if (resolve(dirname(worktreeGitDir)) !== join(commonDir, "worktrees")) {
96
+ return gitRoot;
97
+ }
98
+ // SECURITY: validate gitdir back-link points to our .git
99
+ const backlink = realpathSync(readFileSync(join(worktreeGitDir, "gitdir"), "utf-8").trim());
100
+ if (backlink !== join(realpathSync(gitRoot), ".git")) {
101
+ return gitRoot;
102
+ }
103
+ if (commonDir.endsWith(`${sep}.git`) || commonDir.endsWith("/.git")) {
104
+ return dirname(commonDir).normalize("NFC");
105
+ }
106
+ return commonDir.normalize("NFC");
107
+ }
108
+ catch {
109
+ return gitRoot;
110
+ }
111
+ }
112
+ export function findCanonicalGitRoot(startPath) {
113
+ const root = findGitRoot(startPath);
114
+ if (!root)
115
+ return null;
116
+ return resolveCanonicalRoot(root);
117
+ }
118
+ function getClaudeConfigHomeDir() {
119
+ return (process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude")).normalize("NFC");
120
+ }
121
+ export function getProjectDir(worktree) {
122
+ const canonicalRoot = findCanonicalGitRoot(worktree) ?? worktree;
123
+ return join(getClaudeConfigHomeDir(), "projects", sanitizePath(canonicalRoot));
124
+ }
125
+ export function getMemoryDir(worktree) {
126
+ const memoryDir = join(getProjectDir(worktree), "memory");
127
+ ensureDir(memoryDir);
128
+ return memoryDir;
129
+ }
130
+ export function getMemoryEntrypoint(worktree) {
131
+ return join(getMemoryDir(worktree), ENTRYPOINT_NAME);
132
+ }
133
+ export function isMemoryPath(absolutePath, worktree) {
134
+ const memDir = getMemoryDir(worktree);
135
+ return absolutePath.startsWith(memDir);
136
+ }
137
+ export function ensureDir(dir) {
138
+ if (!existsSync(dir)) {
139
+ mkdirSync(dir, { recursive: true });
140
+ }
141
+ }
@@ -0,0 +1,4 @@
1
+ export type BuildMemorySystemPromptOptions = {
2
+ includeIndex?: boolean;
3
+ };
4
+ export declare function buildMemorySystemPrompt(worktree: string, recalledMemoriesSection?: string, options?: BuildMemorySystemPromptOptions): string;
package/dist/prompt.js ADDED
@@ -0,0 +1,199 @@
1
+ import { MEMORY_TYPES } from "./memory.js";
2
+ import { readIndex, truncateEntrypoint } from "./memory.js";
3
+ import { getMemoryDir, ENTRYPOINT_NAME, MAX_ENTRYPOINT_LINES, getProjectDir } from "./paths.js";
4
+ // Port of Claude Code's MEMORY_FRONTMATTER_EXAMPLE from memoryTypes.ts
5
+ const FRONTMATTER_EXAMPLE = [
6
+ "```markdown",
7
+ "---",
8
+ "name: {{memory name}}",
9
+ "description: {{one-line description — used to decide relevance in future conversations, so be specific}}",
10
+ `type: {{${MEMORY_TYPES.join(", ")}}}`,
11
+ "---",
12
+ "",
13
+ "{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}",
14
+ "```",
15
+ ];
16
+ // Port of Claude Code's TYPES_SECTION_INDIVIDUAL from memoryTypes.ts
17
+ const TYPES_SECTION = [
18
+ "## Types of memory",
19
+ "",
20
+ "There are several discrete types of memory that you can store in your memory system:",
21
+ "",
22
+ "<types>",
23
+ "<type>",
24
+ " <name>user</name>",
25
+ " <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>",
26
+ " <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>",
27
+ " <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>",
28
+ " <examples>",
29
+ " user: I'm a data scientist investigating what logging we have in place",
30
+ " assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]",
31
+ "",
32
+ " user: I've been writing Go for ten years but this is my first time touching the React side of this repo",
33
+ " assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]",
34
+ " </examples>",
35
+ "</type>",
36
+ "<type>",
37
+ " <name>feedback</name>",
38
+ " <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>",
39
+ " <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>",
40
+ " <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>",
41
+ " <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>",
42
+ " <examples>",
43
+ " user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed",
44
+ " assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]",
45
+ "",
46
+ " user: stop summarizing what you just did at the end of every response, I can read the diff",
47
+ " assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]",
48
+ "",
49
+ " user: yeah the single bundled PR was the right call here, splitting this one would've just been churn",
50
+ " 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]",
51
+ " </examples>",
52
+ "</type>",
53
+ "<type>",
54
+ " <name>project</name>",
55
+ " <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>",
56
+ " <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>",
57
+ " <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>",
58
+ " <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>",
59
+ " <examples>",
60
+ " user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch",
61
+ " assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]",
62
+ "",
63
+ " 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",
64
+ " 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]",
65
+ " </examples>",
66
+ "</type>",
67
+ "<type>",
68
+ " <name>reference</name>",
69
+ " <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>",
70
+ " <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>",
71
+ " <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>",
72
+ " <examples>",
73
+ ` user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs`,
74
+ ` assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]`,
75
+ "",
76
+ " 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",
77
+ " assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]",
78
+ " </examples>",
79
+ "</type>",
80
+ "</types>",
81
+ "",
82
+ ].join("\n");
83
+ // Port of Claude Code's WHAT_NOT_TO_SAVE_SECTION from memoryTypes.ts
84
+ const WHAT_NOT_TO_SAVE = [
85
+ "## What NOT to save in memory",
86
+ "",
87
+ "- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.",
88
+ "- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.",
89
+ "- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.",
90
+ "- Anything already documented in AGENTS.md or project config files.",
91
+ "- Ephemeral task details: in-progress work, temporary state, current conversation context.",
92
+ "",
93
+ "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.",
94
+ ].join("\n");
95
+ // Port of Claude Code's WHEN_TO_ACCESS_SECTION from memoryTypes.ts
96
+ const WHEN_TO_ACCESS = [
97
+ "## When to access memories",
98
+ "- When memories seem relevant, or the user references prior-conversation work.",
99
+ "- You MUST access memory when the user explicitly asks you to check, recall, or remember.",
100
+ "- 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.",
101
+ "- 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.",
102
+ ].join("\n");
103
+ // Port of Claude Code's TRUSTING_RECALL_SECTION from memoryTypes.ts
104
+ const TRUSTING_RECALL = [
105
+ "## Before recommending from memory",
106
+ "",
107
+ "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:",
108
+ "",
109
+ "- If the memory names a file path: check the file exists.",
110
+ "- If the memory names a function or flag: grep for it.",
111
+ "- If the user is about to act on your recommendation (not just asking about history), verify first.",
112
+ "",
113
+ '"The memory says X exists" is not the same as "X exists now."',
114
+ "",
115
+ "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.",
116
+ ].join("\n");
117
+ // Port of Claude Code's buildSearchingPastContextSection() from memdir.ts.
118
+ // Guides the model to grep memory files and session transcripts when
119
+ // looking for past context, rather than guessing or hallucinating.
120
+ function buildSearchingPastContextSection(memoryDir, projectDir) {
121
+ const memSearch = `grep -rn "<search term>" ${memoryDir} --include="*.md"`;
122
+ const transcriptSearch = `grep -rn "<search term>" ${projectDir}/ --include="*.jsonl"`;
123
+ return [
124
+ "## Searching past context",
125
+ "",
126
+ "When looking for past context:",
127
+ "1. Search topic files in your memory directory:",
128
+ "```",
129
+ memSearch,
130
+ "```",
131
+ "2. Session transcript logs (last resort — large files, slow):",
132
+ "```",
133
+ transcriptSearch,
134
+ "```",
135
+ "Use narrow search terms (error messages, file paths, function names) rather than broad keywords.",
136
+ "",
137
+ ];
138
+ }
139
+ export function buildMemorySystemPrompt(worktree, recalledMemoriesSection, options = {}) {
140
+ const memoryDir = getMemoryDir(worktree);
141
+ const projectDir = getProjectDir(worktree);
142
+ const indexContent = readIndex(worktree);
143
+ const includeIndex = options.includeIndex ?? true;
144
+ const howToSave = [
145
+ "## How to save memories",
146
+ "",
147
+ "Saving a memory is a two-step process:",
148
+ "",
149
+ '**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:',
150
+ "",
151
+ ...FRONTMATTER_EXAMPLE,
152
+ "",
153
+ `**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}\`.`,
154
+ "",
155
+ `- \`${ENTRYPOINT_NAME}\` is always loaded into your conversation context — lines after ${MAX_ENTRYPOINT_LINES} will be truncated, so keep the index concise`,
156
+ "- Keep the name, description, and type fields in memory files up-to-date with the content",
157
+ "- Organize memory semantically by topic, not chronologically",
158
+ "- Update or remove memories that turn out to be wrong or outdated",
159
+ "- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.",
160
+ ].join("\n");
161
+ const lines = [
162
+ "# Auto Memory",
163
+ "",
164
+ `You have a persistent, file-based memory system at \`${memoryDir}\`. This directory already exists — write to it directly (do not run mkdir or check for its existence).`,
165
+ "",
166
+ "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.",
167
+ "",
168
+ "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.",
169
+ "",
170
+ TYPES_SECTION,
171
+ WHAT_NOT_TO_SAVE,
172
+ "",
173
+ howToSave,
174
+ "",
175
+ WHEN_TO_ACCESS,
176
+ "",
177
+ TRUSTING_RECALL,
178
+ "",
179
+ "## Memory and other forms of persistence",
180
+ "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.",
181
+ "- 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.",
182
+ "- 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.",
183
+ "",
184
+ ...buildSearchingPastContextSection(memoryDir, projectDir),
185
+ ];
186
+ if (includeIndex) {
187
+ if (indexContent.trim()) {
188
+ const { content: truncated } = truncateEntrypoint(indexContent);
189
+ lines.push(`## ${ENTRYPOINT_NAME}`, "", truncated);
190
+ }
191
+ else {
192
+ lines.push(`## ${ENTRYPOINT_NAME}`, "", `Your ${ENTRYPOINT_NAME} is currently empty. When you save new memories, they will appear here.`);
193
+ }
194
+ }
195
+ if (recalledMemoriesSection?.trim()) {
196
+ lines.push("", recalledMemoriesSection);
197
+ }
198
+ return lines.join("\n");
199
+ }
@@ -0,0 +1,11 @@
1
+ export type RecalledMemory = {
2
+ fileName: string;
3
+ filePath: string;
4
+ name: string;
5
+ type: string;
6
+ description: string;
7
+ content: string;
8
+ ageInDays: number;
9
+ };
10
+ export declare function recallRelevantMemories(worktree: string, query?: string, alreadySurfaced?: ReadonlySet<string>, recentTools?: readonly string[]): RecalledMemory[];
11
+ export declare function formatRecalledMemories(memories: RecalledMemory[]): string;
package/dist/recall.js ADDED
@@ -0,0 +1,138 @@
1
+ import { readFileSync } from "fs";
2
+ import { scanMemoryFiles } from "./memoryScan.js";
3
+ import { getMemoryDir } from "./paths.js";
4
+ const MAX_RECALLED_MEMORIES = 5;
5
+ const MAX_MEMORY_LINES = 200;
6
+ const MAX_MEMORY_BYTES = 4096;
7
+ const encoder = new TextEncoder();
8
+ function tokenizeQuery(query) {
9
+ return [...new Set(query.toLowerCase().split(/\s+/).map((token) => token.trim()).filter((token) => token.length >= 2))];
10
+ }
11
+ function readMemoryContent(filePath) {
12
+ try {
13
+ const raw = readFileSync(filePath, "utf-8");
14
+ const trimmed = raw.trim();
15
+ if (!trimmed.startsWith("---"))
16
+ return trimmed;
17
+ const lines = trimmed.split("\n");
18
+ let closingIdx = -1;
19
+ for (let i = 1; i < lines.length; i++) {
20
+ if (lines[i].trimEnd() === "---") {
21
+ closingIdx = i;
22
+ break;
23
+ }
24
+ }
25
+ return closingIdx === -1 ? trimmed : lines.slice(closingIdx + 1).join("\n").trim();
26
+ }
27
+ catch {
28
+ return "";
29
+ }
30
+ }
31
+ function scoreHeader(header, content, terms) {
32
+ if (terms.length === 0)
33
+ return 0;
34
+ const nameHaystack = (header.name ?? "").toLowerCase();
35
+ const descHaystack = (header.description ?? "").toLowerCase();
36
+ const filenameHaystack = header.filename.toLowerCase();
37
+ const contentHaystack = content.toLowerCase();
38
+ let score = 0;
39
+ for (const term of terms) {
40
+ if (nameHaystack.includes(term))
41
+ score += 3;
42
+ if (descHaystack.includes(term))
43
+ score += 3;
44
+ if (filenameHaystack.includes(term))
45
+ score += 1;
46
+ if (contentHaystack.includes(term))
47
+ score += 1;
48
+ }
49
+ return score;
50
+ }
51
+ function truncateMemoryContent(content) {
52
+ const maxLines = content.split("\n").slice(0, MAX_MEMORY_LINES);
53
+ const lineTruncated = maxLines.join("\n");
54
+ if (encoder.encode(lineTruncated).length <= MAX_MEMORY_BYTES) {
55
+ return lineTruncated;
56
+ }
57
+ const lines = lineTruncated.split("\n");
58
+ const kept = [];
59
+ let usedBytes = 0;
60
+ for (const line of lines) {
61
+ const candidate = kept.length === 0 ? line : `\n${line}`;
62
+ const candidateBytes = encoder.encode(candidate).length;
63
+ if (usedBytes + candidateBytes > MAX_MEMORY_BYTES)
64
+ break;
65
+ kept.push(line);
66
+ usedBytes += candidateBytes;
67
+ }
68
+ return kept.join("\n");
69
+ }
70
+ // Port of Claude Code's findRelevantMemories pattern, adapted for
71
+ // keyword-based selection (no LLM side query available in plugin context).
72
+ function isToolReferenceMemory(header, content, recentTools) {
73
+ if (recentTools.length === 0)
74
+ return false;
75
+ const type = header.type;
76
+ if (type !== "reference")
77
+ return false;
78
+ const haystack = `${header.name ?? ""}\n${header.description ?? ""}\n${content}`.toLowerCase();
79
+ const warningSignals = ["warning", "gotcha", "issue", "bug", "caveat", "pitfall", "known issue"];
80
+ if (warningSignals.some((w) => haystack.includes(w)))
81
+ return false;
82
+ const toolHaystack = recentTools.map((t) => t.toLowerCase());
83
+ return toolHaystack.some((tool) => haystack.includes(tool));
84
+ }
85
+ export function recallRelevantMemories(worktree, query, alreadySurfaced = new Set(), recentTools = []) {
86
+ const memoryDir = getMemoryDir(worktree);
87
+ const headers = scanMemoryFiles(memoryDir).filter((h) => !alreadySurfaced.has(`${h.name ?? h.filename.replace(/\.md$/, "").replace(/.*\//, "")}|${h.type ?? "user"}`));
88
+ if (headers.length === 0)
89
+ return [];
90
+ const now = Date.now();
91
+ const terms = query ? tokenizeQuery(query) : [];
92
+ const scored = headers.map((header) => {
93
+ const content = readMemoryContent(header.filePath);
94
+ return {
95
+ header,
96
+ content,
97
+ score: scoreHeader(header, content, terms),
98
+ };
99
+ }).filter(({ header, content }) => !isToolReferenceMemory(header, content, recentTools));
100
+ if (terms.length > 0 && scored.some((s) => s.score > 0)) {
101
+ scored.sort((a, b) => b.score - a.score || b.header.mtimeMs - a.header.mtimeMs);
102
+ }
103
+ else {
104
+ scored.sort((a, b) => b.header.mtimeMs - a.header.mtimeMs);
105
+ }
106
+ return scored.slice(0, MAX_RECALLED_MEMORIES).map(({ header, content }) => {
107
+ const nameFromFilename = header.filename.replace(/\.md$/, "").replace(/.*\//, "");
108
+ return {
109
+ fileName: header.filename,
110
+ filePath: header.filePath,
111
+ name: header.name ?? nameFromFilename,
112
+ type: header.type ?? "user",
113
+ description: header.description ?? "",
114
+ content: truncateMemoryContent(content),
115
+ ageInDays: Math.max(0, Math.floor((now - header.mtimeMs) / (1000 * 60 * 60 * 24))),
116
+ };
117
+ });
118
+ }
119
+ function formatAgeWarning(ageInDays) {
120
+ if (ageInDays <= 1)
121
+ return "";
122
+ 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`;
123
+ }
124
+ export function formatRecalledMemories(memories) {
125
+ if (memories.length === 0)
126
+ return "";
127
+ const sections = memories.map((memory) => {
128
+ const ageWarning = formatAgeWarning(memory.ageInDays);
129
+ return `### ${memory.name} (${memory.type})${ageWarning}\n${memory.content}`;
130
+ });
131
+ return [
132
+ "## Recalled Memories",
133
+ "",
134
+ "The following memories were automatically selected as relevant to this conversation. They may be outdated — verify against current state before relying on them.",
135
+ "",
136
+ sections.join("\n\n"),
137
+ ].join("\n");
138
+ }
package/package.json CHANGED
@@ -1,19 +1,27 @@
1
1
  {
2
2
  "name": "opencode-claude-memory",
3
- "version": "1.6.0",
3
+ "version": "1.6.2",
4
4
  "type": "module",
5
5
  "description": "Claude Code-compatible memory compatibility layer for OpenCode — zero config, local-first, no migration",
6
- "main": "src/index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
7
8
  "bin": {
8
9
  "opencode-memory": "./bin/opencode-memory"
9
10
  },
10
11
  "exports": {
11
- ".": "./src/index.ts"
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "default": "./dist/index.js"
16
+ }
12
17
  },
13
18
  "files": [
14
- "src",
15
- "bin"
19
+ "dist"
16
20
  ],
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.json",
23
+ "prepack": "npm run build"
24
+ },
17
25
  "repository": {
18
26
  "type": "git",
19
27
  "url": "git+https://github.com/kuitos/opencode-claude-memory.git"
@@ -36,6 +44,7 @@
36
44
  },
37
45
  "devDependencies": {
38
46
  "bun-types": "^1.3.11",
39
- "@opencode-ai/plugin": "^1.3.10"
47
+ "@opencode-ai/plugin": "^1.3.10",
48
+ "typescript": "^6.0.2"
40
49
  }
41
50
  }