@nandoblanco/opencode-local-memory 1.1.1 → 1.3.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/CHANGELOG.md +35 -0
- package/README.md +34 -10
- package/dist/gui-experimental.cjs +1 -0
- package/gui.css +635 -0
- package/gui.tsx +1313 -0
- package/index.js +524 -51
- package/package.json +24 -3
- package/rpc.d.ts +140 -0
- package/rpc.js +221 -0
- package/tui.ts +682 -100
package/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import path from "node:path";
|
|
|
6
6
|
import os from "node:os";
|
|
7
7
|
import { execFile } from "node:child_process";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { MemoryRpc } from "./rpc.js";
|
|
9
10
|
|
|
10
11
|
const __filename = fileURLToPath(import.meta.url);
|
|
11
12
|
const __dirname = path.dirname(__filename);
|
|
@@ -483,15 +484,15 @@ async function getEmbedder() {
|
|
|
483
484
|
embedderPromise = (async function () {
|
|
484
485
|
let pipelineFn;
|
|
485
486
|
try {
|
|
486
|
-
const mod = await import("@
|
|
487
|
+
const mod = await import("@huggingface/transformers");
|
|
487
488
|
pipelineFn = mod.pipeline;
|
|
488
489
|
} catch {
|
|
489
|
-
const fallbackPath = path.resolve(__dirname, "node_modules/@
|
|
490
|
+
const fallbackPath = path.resolve(__dirname, "node_modules/@huggingface/transformers/dist/transformers.node.mjs");
|
|
490
491
|
const fallbackUrl = new URL("file:///" + fallbackPath.replace(/\\/g, "/")).href;
|
|
491
492
|
const mod = await import(fallbackUrl);
|
|
492
493
|
pipelineFn = mod.pipeline;
|
|
493
494
|
}
|
|
494
|
-
return pipelineFn("feature-extraction", "Xenova/all-MiniLM-L6-v2");
|
|
495
|
+
return pipelineFn("feature-extraction", "Xenova/all-MiniLM-L6-v2", { device: "cpu", dtype: "q8" });
|
|
495
496
|
})().catch(function (err) {
|
|
496
497
|
embedderPromise = null;
|
|
497
498
|
throw err;
|
|
@@ -621,6 +622,13 @@ function parseSessionEntries(rootDir) {
|
|
|
621
622
|
const base = file.replace(/\.md$/, "");
|
|
622
623
|
const titleMatch = raw.match(/^#\s+(.+)$/m);
|
|
623
624
|
const title = titleMatch ? titleMatch[1].trim() : base;
|
|
625
|
+
if (
|
|
626
|
+
title.startsWith("Auto Compaction Checkpoint (") &&
|
|
627
|
+
raw.includes("Automatic checkpoint captured at session compaction.")
|
|
628
|
+
) {
|
|
629
|
+
parsedFileCache.set(fullPath, { mtimeMs: stat.mtimeMs, entries: [] });
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
624
632
|
const dateMatch = base.match(/^(\d{4}-\d{2}-\d{2})_(.+)$/);
|
|
625
633
|
const date = dateMatch ? dateMatch[1] : "";
|
|
626
634
|
const slug = dateMatch ? dateMatch[2] : base;
|
|
@@ -642,12 +650,18 @@ function parseSessionEntries(rootDir) {
|
|
|
642
650
|
const re = new RegExp("##\\s+" + heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\s*\\n([\\s\\S]*?)(?=\\n##\\s+|$)", "i");
|
|
643
651
|
const m = raw.match(re);
|
|
644
652
|
if (m && m[1].trim()) {
|
|
645
|
-
const
|
|
646
|
-
|
|
653
|
+
const stripped = m[1]
|
|
654
|
+
.replace(/^#\s+Session Handoff:[^\n]*\n?/gim, "")
|
|
655
|
+
.replace(/^-\s+\*\*(?:Date|Previous Session ID|Project|Working Directory|Reason for Handoff)\*\*:[^\n]*\n?/gim, "")
|
|
656
|
+
.replace(/^#{2,4}\s+/gm, "");
|
|
657
|
+
const cleaned = stripped.trim().replace(/\n+/g, " ").replace(/\s+/g, " ");
|
|
658
|
+
if (cleaned) {
|
|
659
|
+
sections.push(heading + ": " + cleaned);
|
|
660
|
+
}
|
|
647
661
|
}
|
|
648
662
|
}
|
|
649
663
|
|
|
650
|
-
const factText = title + " — " + (sections.join(" | ").slice(0,
|
|
664
|
+
const factText = title + " — " + (sections.join(" | ").slice(0, 240) || raw.replace(/\s+/g, " ").slice(0, 240));
|
|
651
665
|
const entry = {
|
|
652
666
|
id: "session:" + base,
|
|
653
667
|
date: date,
|
|
@@ -1263,10 +1277,19 @@ async function storeMemoryFact(rootDir, input) {
|
|
|
1263
1277
|
const rawTags = Array.isArray(input.tags)
|
|
1264
1278
|
? input.tags.map(function (t) { return String(t).trim(); }).filter(Boolean).join(", ")
|
|
1265
1279
|
: String(input.tags || rawTopic).trim();
|
|
1266
|
-
|
|
1280
|
+
let tagsList = rawTags.replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, " ").trim() || rawTopic;
|
|
1281
|
+
if (input.core === false) {
|
|
1282
|
+
tagsList = tagsList
|
|
1283
|
+
.split(",")
|
|
1284
|
+
.map(function (t) { return t.trim(); })
|
|
1285
|
+
.filter(function (t) { return t && t.toLowerCase() !== "core"; })
|
|
1286
|
+
.join(", ") || rawTopic;
|
|
1287
|
+
}
|
|
1267
1288
|
const cleanFact = String(input.fact || "").replace(/\s+/g, " ").trim();
|
|
1268
1289
|
const projectScope = normalizeProjectScope(input.project);
|
|
1269
|
-
const isCore = input.core ===
|
|
1290
|
+
const isCore = input.core === false
|
|
1291
|
+
? false
|
|
1292
|
+
: (input.core === true || /(?:^|,)\s*core\s*(?:,|$)/i.test(tagsList));
|
|
1270
1293
|
|
|
1271
1294
|
const blockLines = [
|
|
1272
1295
|
"",
|
|
@@ -1321,6 +1344,71 @@ async function storeMemoryFact(rootDir, input) {
|
|
|
1321
1344
|
});
|
|
1322
1345
|
}
|
|
1323
1346
|
|
|
1347
|
+
async function maintainMemory(rootDir, options) {
|
|
1348
|
+
const opts = options || {};
|
|
1349
|
+
ensureMemoryLayout(rootDir);
|
|
1350
|
+
const sessionDir = path.join(rootDir, "sessions");
|
|
1351
|
+
const idsToDelete = [];
|
|
1352
|
+
|
|
1353
|
+
if (fs.existsSync(sessionDir)) {
|
|
1354
|
+
const files = fs.readdirSync(sessionDir).filter(function (f) {
|
|
1355
|
+
return f.endsWith(".md") && f.toLowerCase() !== "readme.md";
|
|
1356
|
+
});
|
|
1357
|
+
for (const file of files) {
|
|
1358
|
+
const fullPath = path.join(sessionDir, file);
|
|
1359
|
+
try {
|
|
1360
|
+
const raw = fs.readFileSync(fullPath, "utf8");
|
|
1361
|
+
if (
|
|
1362
|
+
raw.includes("# Auto Compaction Checkpoint (") &&
|
|
1363
|
+
raw.includes("Automatic checkpoint captured at session compaction.")
|
|
1364
|
+
) {
|
|
1365
|
+
idsToDelete.push("session:" + file.replace(/\.md$/, ""));
|
|
1366
|
+
}
|
|
1367
|
+
} catch {
|
|
1368
|
+
// ignore read error
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
const topics = parseTopicEntries(rootDir);
|
|
1374
|
+
const seenByProjectFact = new Map();
|
|
1375
|
+
for (const entry of topics) {
|
|
1376
|
+
if (opts.pruneImportedRules && /\bimported\b/i.test(entry.tags || "")) {
|
|
1377
|
+
idsToDelete.push(entry.id);
|
|
1378
|
+
continue;
|
|
1379
|
+
}
|
|
1380
|
+
const normFact = String(entry.fact || "").toLowerCase().replace(/\s+/g, " ").trim();
|
|
1381
|
+
const normProj = normalizeProjectScope(entry.project || "global");
|
|
1382
|
+
const dedupKey = normProj + "::" + normFact;
|
|
1383
|
+
if (seenByProjectFact.has(dedupKey)) {
|
|
1384
|
+
idsToDelete.push(seenByProjectFact.get(dedupKey));
|
|
1385
|
+
}
|
|
1386
|
+
seenByProjectFact.set(dedupKey, entry.id);
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
let deletedCount = 0;
|
|
1390
|
+
if (idsToDelete.length > 0) {
|
|
1391
|
+
const delRes = await deleteMemoryEntry(rootDir, idsToDelete);
|
|
1392
|
+
deletedCount = delRes.deleted.length;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
const syncResult = await syncVectors(rootDir);
|
|
1396
|
+
const stampFile = path.join(rootDir, ".last-maintain");
|
|
1397
|
+
try {
|
|
1398
|
+
fs.writeFileSync(stampFile, new Date().toISOString() + "\n", "utf8");
|
|
1399
|
+
} catch {
|
|
1400
|
+
// ignore stamp write error
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
return {
|
|
1404
|
+
deletedCount: deletedCount,
|
|
1405
|
+
deletedIds: idsToDelete,
|
|
1406
|
+
total: syncResult.total,
|
|
1407
|
+
embedded: syncResult.embedded,
|
|
1408
|
+
reused: syncResult.reused
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1324
1412
|
async function storeSessionCheckpoint(rootDir, input) {
|
|
1325
1413
|
ensureMemoryLayout(rootDir);
|
|
1326
1414
|
const sessionDir = path.join(rootDir, "sessions");
|
|
@@ -1962,29 +2050,263 @@ async function importExistingMemory(rootDir, options) {
|
|
|
1962
2050
|
};
|
|
1963
2051
|
}
|
|
1964
2052
|
|
|
2053
|
+
function extractUserMessageText(msg) {
|
|
2054
|
+
if (!msg || msg.role !== "user") return "";
|
|
2055
|
+
if (typeof msg.content === "string") return msg.content;
|
|
2056
|
+
if (typeof msg.text === "string") return msg.text;
|
|
2057
|
+
if (Array.isArray(msg.content)) {
|
|
2058
|
+
const textParts = msg.content
|
|
2059
|
+
.filter(function (p) { return p && (p.type === "text" || typeof p.text === "string"); })
|
|
2060
|
+
.map(function (p) { return p.text || ""; });
|
|
2061
|
+
if (textParts.length > 0) return textParts.join(" ");
|
|
2062
|
+
}
|
|
2063
|
+
if (Array.isArray(msg.parts)) {
|
|
2064
|
+
const textParts = msg.parts
|
|
2065
|
+
.filter(function (p) { return p && p.type === "text"; })
|
|
2066
|
+
.map(function (p) { return p.text || ""; });
|
|
2067
|
+
if (textParts.length > 0) return textParts.join(" ");
|
|
2068
|
+
}
|
|
2069
|
+
return "";
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
function extractFirstUserText(messages) {
|
|
2073
|
+
if (!Array.isArray(messages)) return "";
|
|
2074
|
+
for (let i = 0; i < messages.length; i++) {
|
|
2075
|
+
const text = extractUserMessageText(messages[i]);
|
|
2076
|
+
if (text) return text;
|
|
2077
|
+
}
|
|
2078
|
+
return "";
|
|
2079
|
+
}
|
|
2080
|
+
|
|
1965
2081
|
function extractLastUserText(messages) {
|
|
1966
2082
|
if (!Array.isArray(messages)) return "";
|
|
1967
2083
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1968
|
-
const
|
|
1969
|
-
if (
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
2084
|
+
const text = extractUserMessageText(messages[i]);
|
|
2085
|
+
if (text) return text;
|
|
2086
|
+
}
|
|
2087
|
+
return "";
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
function isSafeSubPath(parentDir, targetPath) {
|
|
2091
|
+
const rel = path.relative(path.resolve(parentDir), path.resolve(targetPath));
|
|
2092
|
+
return Boolean(rel && !rel.startsWith("..") && !path.isAbsolute(rel));
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
function isSafeRegexPattern(pattern) {
|
|
2096
|
+
if (!pattern || pattern.length > 256) return false;
|
|
2097
|
+
if (/(\([^()]*[+*?][^()]*\))\s*[+*?{]/.test(pattern)) return false;
|
|
2098
|
+
return true;
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
function readSessionMarkdown(rootDir, relFile) {
|
|
2102
|
+
try {
|
|
2103
|
+
const cleanRel = String(relFile || "").replace(/\\/g, "/");
|
|
2104
|
+
if (!cleanRel.startsWith("sessions/")) return "";
|
|
2105
|
+
const fullPath = path.resolve(rootDir, cleanRel);
|
|
2106
|
+
if (!isSafeSubPath(rootDir, fullPath)) return "";
|
|
2107
|
+
if (fs.existsSync(fullPath)) {
|
|
2108
|
+
return fs.readFileSync(fullPath, "utf8").replace(/\r\n/g, "\n").trim();
|
|
2109
|
+
}
|
|
2110
|
+
} catch {
|
|
2111
|
+
// ignore read error
|
|
2112
|
+
}
|
|
2113
|
+
return "";
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
function parseInlineMemoryFilters(rawQ, tFilter, topFilter, mFilter, projFilter, coreOnlyFlag) {
|
|
2117
|
+
let effType = tFilter || "all";
|
|
2118
|
+
let effTopic = topFilter || "all";
|
|
2119
|
+
let effMode = mFilter || "hybrid";
|
|
2120
|
+
let effProject = projFilter || "all";
|
|
2121
|
+
let effCoreOnly = Boolean(coreOnlyFlag) || effType === "core";
|
|
2122
|
+
const tokens = String(rawQ || "").trim().split(/\s+/).filter(Boolean);
|
|
2123
|
+
const cleanTokens = [];
|
|
2124
|
+
|
|
2125
|
+
for (const tok of tokens) {
|
|
2126
|
+
const lower = tok.toLowerCase();
|
|
2127
|
+
if (lower === "type:topics" || lower === "type:facts" || lower === "in:topics") {
|
|
2128
|
+
effType = "topics";
|
|
2129
|
+
} else if (lower === "type:sessions" || lower === "in:sessions") {
|
|
2130
|
+
effType = "sessions";
|
|
2131
|
+
} else if (lower === "type:core" || lower === "in:core") {
|
|
2132
|
+
effType = "core";
|
|
2133
|
+
effCoreOnly = true;
|
|
2134
|
+
} else if (lower === "type:all") {
|
|
2135
|
+
effType = "all";
|
|
2136
|
+
} else if (lower === "core:true" || lower === "is:core") {
|
|
2137
|
+
effCoreOnly = true;
|
|
2138
|
+
} else if (lower.startsWith("project:")) {
|
|
2139
|
+
const val = lower.slice(8).trim();
|
|
2140
|
+
if (val) effProject = val;
|
|
2141
|
+
} else if (lower.startsWith("topic:")) {
|
|
2142
|
+
const val = lower.slice(6).trim();
|
|
2143
|
+
if (val) effTopic = val;
|
|
2144
|
+
} else if (lower.startsWith("re:") && tok.length > 3) {
|
|
2145
|
+
effMode = "regex";
|
|
2146
|
+
cleanTokens.push(tok.slice(3));
|
|
2147
|
+
} else {
|
|
2148
|
+
cleanTokens.push(tok);
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
return {
|
|
2153
|
+
cleanQ: cleanTokens.join(" ").trim(),
|
|
2154
|
+
effType: effType,
|
|
2155
|
+
effTopic: effTopic,
|
|
2156
|
+
effMode: effMode,
|
|
2157
|
+
effProject: effProject,
|
|
2158
|
+
effCoreOnly: effCoreOnly,
|
|
2159
|
+
};
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
function sanitizeRpcEntry(entry) {
|
|
2163
|
+
const out = {
|
|
2164
|
+
id: String(entry.id || ""),
|
|
2165
|
+
date: String(entry.date || ""),
|
|
2166
|
+
file: String(entry.file || ""),
|
|
2167
|
+
tags: String(entry.tags || ""),
|
|
2168
|
+
fact: String(entry.fact || ""),
|
|
2169
|
+
};
|
|
2170
|
+
if (entry.project) out.project = String(entry.project);
|
|
2171
|
+
if (entry.core) out.core = true;
|
|
2172
|
+
return out;
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
async function executeMemoryQuery(rootDir, input) {
|
|
2176
|
+
const opts = input || {};
|
|
2177
|
+
const entries = loadCachedVectors(rootDir) || [];
|
|
2178
|
+
const limit = Math.max(1, Math.min(200, Number(opts.limit) || 100));
|
|
2179
|
+
const parsed = parseInlineMemoryFilters(
|
|
2180
|
+
opts.query || "",
|
|
2181
|
+
opts.typeFilter || "all",
|
|
2182
|
+
opts.topicFilter || "all",
|
|
2183
|
+
opts.mode || "hybrid",
|
|
2184
|
+
opts.projectFilter || "all",
|
|
2185
|
+
opts.coreOnly
|
|
2186
|
+
);
|
|
2187
|
+
const q = parsed.cleanQ;
|
|
2188
|
+
const effType = parsed.effType;
|
|
2189
|
+
const effTopic = parsed.effTopic;
|
|
2190
|
+
const effMode = parsed.effMode;
|
|
2191
|
+
const effProject = parsed.effProject;
|
|
2192
|
+
const effCoreOnly = parsed.effCoreOnly;
|
|
2193
|
+
|
|
2194
|
+
let coreCount = 0;
|
|
2195
|
+
let topicsCount = 0;
|
|
2196
|
+
let sessionsCount = 0;
|
|
2197
|
+
const projectSet = new Set(["global"]);
|
|
2198
|
+
|
|
2199
|
+
for (const e of entries) {
|
|
2200
|
+
if (e.core) coreCount++;
|
|
2201
|
+
if (String(e.file || "").startsWith("topics/")) topicsCount++;
|
|
2202
|
+
if (String(e.file || "").startsWith("sessions/")) sessionsCount++;
|
|
2203
|
+
if (e.project && e.project !== "global") projectSet.add(String(e.project));
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
const matchesSubset = function (e) {
|
|
2207
|
+
if (effType === "core" && !e.core) return false;
|
|
2208
|
+
if (effType === "topics" && !String(e.file || "").startsWith("topics/")) return false;
|
|
2209
|
+
if (effType === "sessions" && !String(e.file || "").startsWith("sessions/")) return false;
|
|
2210
|
+
if (effTopic !== "all" && e.file !== "topics/" + effTopic + ".md") return false;
|
|
2211
|
+
if (effCoreOnly && !e.core) return false;
|
|
2212
|
+
if (effProject !== "all" && !matchesProjectScope(e.project, effProject, false)) return false;
|
|
2213
|
+
return true;
|
|
2214
|
+
};
|
|
2215
|
+
|
|
2216
|
+
const subset = entries.filter(matchesSubset);
|
|
2217
|
+
let hits = [];
|
|
2218
|
+
|
|
2219
|
+
if (!q) {
|
|
2220
|
+
const topicPart = subset.filter(function (e) { return !String(e.file || "").startsWith("sessions/"); }).reverse();
|
|
2221
|
+
const sessionPart = subset.filter(function (e) { return String(e.file || "").startsWith("sessions/"); }).reverse();
|
|
2222
|
+
hits = topicPart
|
|
2223
|
+
.concat(sessionPart)
|
|
2224
|
+
.slice(0, limit)
|
|
2225
|
+
.map(function (e) {
|
|
2226
|
+
return { score: 1, semanticScore: 0, entry: sanitizeRpcEntry(e) };
|
|
2227
|
+
});
|
|
2228
|
+
} else if (effMode === "regex" || (q.startsWith("/") && q.lastIndexOf("/") > 0)) {
|
|
2229
|
+
try {
|
|
2230
|
+
const lastSlash = q.startsWith("/") ? q.lastIndexOf("/") : -1;
|
|
2231
|
+
const pattern = lastSlash > 0 ? q.slice(1, lastSlash) : q;
|
|
2232
|
+
if (isSafeRegexPattern(pattern)) {
|
|
2233
|
+
const flags = lastSlash > 0 ? q.slice(lastSlash + 1) || "i" : "i";
|
|
2234
|
+
const re = new RegExp(pattern, flags);
|
|
2235
|
+
hits = subset
|
|
2236
|
+
.filter(function (e) {
|
|
2237
|
+
re.lastIndex = 0;
|
|
2238
|
+
return re.test(e._haystack || (e.id + " " + e.tags + " " + e.fact + " " + e.file));
|
|
2239
|
+
})
|
|
2240
|
+
.slice(0, limit)
|
|
2241
|
+
.map(function (e) {
|
|
2242
|
+
return { score: 1, semanticScore: 0, entry: sanitizeRpcEntry(e) };
|
|
2243
|
+
});
|
|
1978
2244
|
}
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
2245
|
+
} catch {
|
|
2246
|
+
hits = [];
|
|
2247
|
+
}
|
|
2248
|
+
} else {
|
|
2249
|
+
const lowerQ = q.toLowerCase();
|
|
2250
|
+
const words = lowerQ.split(/\s+/).filter(function (w) { return w.length >= 2; });
|
|
2251
|
+
const lexicalHits = [];
|
|
2252
|
+
for (const e of subset) {
|
|
2253
|
+
const hay = e._haystack || (e.id + " " + e.tags + " " + e.fact + " " + e.file).toLowerCase();
|
|
2254
|
+
let lex = 0;
|
|
2255
|
+
if (hay.includes(lowerQ)) {
|
|
2256
|
+
lex = 0.9;
|
|
2257
|
+
} else if (words.length > 0) {
|
|
2258
|
+
let matched = 0;
|
|
2259
|
+
for (const w of words) {
|
|
2260
|
+
if (hay.includes(w)) matched++;
|
|
2261
|
+
}
|
|
2262
|
+
if (matched > 0) lex = (matched / words.length) * 0.75;
|
|
1984
2263
|
}
|
|
2264
|
+
if (lex > 0) {
|
|
2265
|
+
lexicalHits.push({ score: lex, semanticScore: 0, entry: sanitizeRpcEntry(e) });
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
lexicalHits.sort(function (a, b) { return b.score - a.score; });
|
|
2269
|
+
|
|
2270
|
+
if (effMode === "hybrid" && q.length >= 2) {
|
|
2271
|
+
try {
|
|
2272
|
+
const semHits = await searchMemory(rootDir, q, "hybrid", limit, {
|
|
2273
|
+
project: effProject,
|
|
2274
|
+
includeGlobal: effProject === "all",
|
|
2275
|
+
coreOnly: effCoreOnly,
|
|
2276
|
+
});
|
|
2277
|
+
const filteredSem = semHits
|
|
2278
|
+
.filter(function (h) {
|
|
2279
|
+
return matchesSubset(h.entry) && h.score >= 0.22;
|
|
2280
|
+
})
|
|
2281
|
+
.slice(0, limit)
|
|
2282
|
+
.map(function (h) {
|
|
2283
|
+
return {
|
|
2284
|
+
score: Number(h.score || 0),
|
|
2285
|
+
semanticScore: Number(h.semanticScore || 0),
|
|
2286
|
+
entry: sanitizeRpcEntry(h.entry),
|
|
2287
|
+
};
|
|
2288
|
+
});
|
|
2289
|
+
hits = filteredSem.length > 0 ? filteredSem : lexicalHits.slice(0, limit);
|
|
2290
|
+
} catch {
|
|
2291
|
+
hits = lexicalHits.slice(0, limit);
|
|
2292
|
+
}
|
|
2293
|
+
} else {
|
|
2294
|
+
hits = lexicalHits.slice(0, limit);
|
|
1985
2295
|
}
|
|
1986
2296
|
}
|
|
1987
|
-
|
|
2297
|
+
|
|
2298
|
+
return JSON.parse(
|
|
2299
|
+
JSON.stringify({
|
|
2300
|
+
rootDir: rootDir,
|
|
2301
|
+
totalEntries: entries.length,
|
|
2302
|
+
coreCount: coreCount,
|
|
2303
|
+
topicsCount: topicsCount,
|
|
2304
|
+
sessionsCount: sessionsCount,
|
|
2305
|
+
topics: getTopicSlugs(rootDir) || [],
|
|
2306
|
+
projects: Array.from(projectSet),
|
|
2307
|
+
hits: hits,
|
|
2308
|
+
})
|
|
2309
|
+
);
|
|
1988
2310
|
}
|
|
1989
2311
|
|
|
1990
2312
|
function createPluginDefinition() {
|
|
@@ -2006,6 +2328,75 @@ function createPluginDefinition() {
|
|
|
2006
2328
|
|
|
2007
2329
|
const registrations = [];
|
|
2008
2330
|
|
|
2331
|
+
if (ctx && ctx.rpc && typeof ctx.rpc.register === "function") {
|
|
2332
|
+
const rpcReg = await ctx.rpc.register(MemoryRpc, {
|
|
2333
|
+
async query(input) {
|
|
2334
|
+
return executeMemoryQuery(rootDir, input);
|
|
2335
|
+
},
|
|
2336
|
+
async store(input) {
|
|
2337
|
+
const saved = await storeMemoryFact(rootDir, input);
|
|
2338
|
+
return JSON.parse(
|
|
2339
|
+
JSON.stringify({
|
|
2340
|
+
entry: {
|
|
2341
|
+
id: String(saved.id || ""),
|
|
2342
|
+
date: String(saved.date || ""),
|
|
2343
|
+
file: String(saved.file || ""),
|
|
2344
|
+
tags: String(saved.tags || ""),
|
|
2345
|
+
fact: String(saved.fact || ""),
|
|
2346
|
+
project: String(saved.project || "global"),
|
|
2347
|
+
core: Boolean(saved.core),
|
|
2348
|
+
updated: Boolean(saved.updated),
|
|
2349
|
+
superseded: Array.isArray(saved.superseded) ? saved.superseded : [],
|
|
2350
|
+
},
|
|
2351
|
+
})
|
|
2352
|
+
);
|
|
2353
|
+
},
|
|
2354
|
+
async remove(input) {
|
|
2355
|
+
const res = await deleteMemoryEntry(rootDir, input && input.id);
|
|
2356
|
+
return JSON.parse(
|
|
2357
|
+
JSON.stringify({
|
|
2358
|
+
deleted: Array.isArray(res.deleted) ? res.deleted : [],
|
|
2359
|
+
notFound: Array.isArray(res.notFound) ? res.notFound : [],
|
|
2360
|
+
total: Number(res.total || 0),
|
|
2361
|
+
})
|
|
2362
|
+
);
|
|
2363
|
+
},
|
|
2364
|
+
async sync() {
|
|
2365
|
+
const res = await syncVectors(rootDir);
|
|
2366
|
+
return JSON.parse(
|
|
2367
|
+
JSON.stringify({
|
|
2368
|
+
total: Number(res.total || 0),
|
|
2369
|
+
embedded: Number(res.embedded || 0),
|
|
2370
|
+
reused: Number(res.reused || 0),
|
|
2371
|
+
vecFile: String(res.vecFile || path.join(rootDir, "vectors.json")),
|
|
2372
|
+
})
|
|
2373
|
+
);
|
|
2374
|
+
},
|
|
2375
|
+
async importMemory(input) {
|
|
2376
|
+
const res = await importExistingMemory(rootDir, {
|
|
2377
|
+
limit: input && input.limit ? Number(input.limit) : undefined,
|
|
2378
|
+
});
|
|
2379
|
+
return JSON.parse(
|
|
2380
|
+
JSON.stringify({
|
|
2381
|
+
importedFactsCount: Array.isArray(res.importedFacts) ? res.importedFacts.length : 0,
|
|
2382
|
+
skippedFacts: Number(res.skippedFacts || 0),
|
|
2383
|
+
importedSessionsCount: Array.isArray(res.importedSessions) ? res.importedSessions.length : 0,
|
|
2384
|
+
skippedSessions: Number(res.skippedSessions || 0),
|
|
2385
|
+
total: Number(res.syncResult && res.syncResult.total ? res.syncResult.total : 0),
|
|
2386
|
+
})
|
|
2387
|
+
);
|
|
2388
|
+
},
|
|
2389
|
+
async getSessionMarkdown(input) {
|
|
2390
|
+
const relFile = String((input && input.file) || "");
|
|
2391
|
+
return {
|
|
2392
|
+
file: relFile,
|
|
2393
|
+
markdown: readSessionMarkdown(rootDir, relFile),
|
|
2394
|
+
};
|
|
2395
|
+
},
|
|
2396
|
+
});
|
|
2397
|
+
if (rpcReg) registrations.push(rpcReg);
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2009
2400
|
if (ctx && ctx.tool && typeof ctx.tool.transform === "function") {
|
|
2010
2401
|
const toolReg = await ctx.tool.transform(function (editor) {
|
|
2011
2402
|
editor.add({
|
|
@@ -2183,13 +2574,36 @@ function createPluginDefinition() {
|
|
|
2183
2574
|
}
|
|
2184
2575
|
|
|
2185
2576
|
if (ctx && ctx.session && typeof ctx.session.hook === "function") {
|
|
2577
|
+
const sessionContextCache = new Map();
|
|
2578
|
+
const lastSessionTextByProject = new Map();
|
|
2186
2579
|
const ctxReg = await ctx.session.hook("context", async function (event) {
|
|
2187
2580
|
const activeProject = (event && event.directory) || defaultProject || "global";
|
|
2188
|
-
const
|
|
2189
|
-
const
|
|
2190
|
-
|
|
2581
|
+
const projectScope = normalizeProjectScope(activeProject);
|
|
2582
|
+
const sessionId = event && (event.sessionID || event.sessionId || (event.session && event.session.id))
|
|
2583
|
+
? String(event.sessionID || event.sessionId || event.session.id)
|
|
2584
|
+
: "";
|
|
2585
|
+
const userText = extractFirstUserText(event && event.messages);
|
|
2586
|
+
const trimmedFirst = String(userText || "").trim();
|
|
2587
|
+
const isCompressedHead = trimmedFirst.startsWith("[Compressed conversation section]");
|
|
2588
|
+
|
|
2589
|
+
if (sessionId && sessionContextCache.has(sessionId)) {
|
|
2590
|
+
if (Array.isArray(event.system)) {
|
|
2591
|
+
event.system.push({ type: "text", text: sessionContextCache.get(sessionId) });
|
|
2592
|
+
}
|
|
2593
|
+
return;
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2596
|
+
if (!sessionId && isCompressedHead && lastSessionTextByProject.has(projectScope)) {
|
|
2191
2597
|
if (Array.isArray(event.system)) {
|
|
2192
|
-
event.system.push({ type: "text", text:
|
|
2598
|
+
event.system.push({ type: "text", text: lastSessionTextByProject.get(projectScope) });
|
|
2599
|
+
}
|
|
2600
|
+
return;
|
|
2601
|
+
}
|
|
2602
|
+
|
|
2603
|
+
const ctxKey = (sessionId || trimmedFirst) + "::" + projectScope;
|
|
2604
|
+
if (sessionContextCache.has(ctxKey)) {
|
|
2605
|
+
if (Array.isArray(event.system)) {
|
|
2606
|
+
event.system.push({ type: "text", text: sessionContextCache.get(ctxKey) });
|
|
2193
2607
|
}
|
|
2194
2608
|
return;
|
|
2195
2609
|
}
|
|
@@ -2198,25 +2612,18 @@ function createPluginDefinition() {
|
|
|
2198
2612
|
const lines = [
|
|
2199
2613
|
"<local-memory-plugin>",
|
|
2200
2614
|
"Persistent memory (`opencode-local-memory`) is active at: " + rootDir,
|
|
2201
|
-
"Available topics: " + (topicSlugs.join(", ") || "preferences, decisions, environment, agent-behavior") + " (or pass any new topic slug
|
|
2615
|
+
"Available topics: " + (topicSlugs.join(", ") || "preferences, decisions, environment, agent-behavior") + " (or pass any new topic slug).",
|
|
2202
2616
|
"",
|
|
2203
|
-
"AUTOMATIC STORAGE (via `memory_store` / `memory_delete`
|
|
2204
|
-
"
|
|
2205
|
-
"- User states a preference, convention, or 'always/never do X' rule",
|
|
2206
|
-
"- An architecture, workflow, or design decision is made (yours or theirs)",
|
|
2207
|
-
"- A non-obvious environment, path, port, or tooling fact is discovered",
|
|
2208
|
-
"- A recurring correction or pattern emerges",
|
|
2209
|
-
"- The user has to correct you or repeat an instruction (store it so it never needs repeating)",
|
|
2210
|
-
"- When replacing an outdated fact, pass `id` to update in-place or `supersedes: '<old-id>'` (or call `memory_delete`) so stale facts never pollute recall.",
|
|
2211
|
-
"Hard gate: before finishing every task, check if any trigger above fired. If it did, call `memory_store` NOW — never promise to remember later. Do NOT store trivial exchanges, transient debugging steps, duplicates, or secrets.",
|
|
2617
|
+
"AUTOMATIC STORAGE (via `memory_store` / `memory_delete` — no prompting needed):",
|
|
2618
|
+
"Before your final response, call `memory_store` in the SAME turn whenever: (1) user states a preference/convention/rule, (2) an architecture or workflow decision is made, (3) a non-obvious environment/path/port/tooling fact is found, or (4) the user corrects you. Pass `id` or `supersedes` (or `memory_delete`) when replacing outdated facts. Never store trivial exchanges, transient debugging steps, duplicates of AGENTS.md, or secrets.",
|
|
2212
2619
|
"",
|
|
2213
2620
|
"WHERE TO STORE:",
|
|
2214
|
-
"- Global (`
|
|
2215
|
-
"- Project-scoped (`
|
|
2621
|
+
"- Global (`project: 'global'`): cross-project coding style, tooling preferences, agent behavior, and environment facts. Pass `core: true` only for critical invariants that are NOT already in AGENTS.md.",
|
|
2622
|
+
"- Project-scoped (`project: '<repo-or-path>'`): project-specific architecture, asset IDs, endpoints, or conventions.",
|
|
2216
2623
|
"",
|
|
2217
2624
|
"AUTOMATIC RECALL & CHECKPOINTS:",
|
|
2218
|
-
"-
|
|
2219
|
-
"-
|
|
2625
|
+
"- Call `memory_search` (`mode: 'hybrid' | 'semantic' | 'grep'`) when the user references past work or deeper recall is needed.",
|
|
2626
|
+
"- At the end of significant work sessions, call `memory_checkpoint` with `slug`, `title`, and a distilled `summary`."
|
|
2220
2627
|
];
|
|
2221
2628
|
|
|
2222
2629
|
const coreMemories = getCoreMemories(rootDir, activeProject, userText);
|
|
@@ -2230,10 +2637,17 @@ function createPluginDefinition() {
|
|
|
2230
2637
|
}
|
|
2231
2638
|
|
|
2232
2639
|
if (userText && userText.trim().length >= 5) {
|
|
2233
|
-
const hits = await searchMemory(rootDir, userText, "hybrid", topK, { project: activeProject }).catch(function () { return []; });
|
|
2234
|
-
const relevant =
|
|
2235
|
-
|
|
2236
|
-
|
|
2640
|
+
const hits = await searchMemory(rootDir, userText, "hybrid", Math.max(topK * 2, 10), { project: activeProject }).catch(function () { return []; });
|
|
2641
|
+
const relevant = [];
|
|
2642
|
+
let sessionCount = 0;
|
|
2643
|
+
for (const h of hits) {
|
|
2644
|
+
if (h.score < minScore || coreIds.has(h.entry.id)) continue;
|
|
2645
|
+
const isSession = String(h.entry.id || "").startsWith("session:");
|
|
2646
|
+
if (isSession && sessionCount >= 2) continue;
|
|
2647
|
+
if (isSession) sessionCount++;
|
|
2648
|
+
relevant.push(h);
|
|
2649
|
+
if (relevant.length >= topK) break;
|
|
2650
|
+
}
|
|
2237
2651
|
if (relevant.length > 0) {
|
|
2238
2652
|
lines.push("Auto-recalled memories for this prompt:");
|
|
2239
2653
|
for (const h of relevant) {
|
|
@@ -2243,15 +2657,23 @@ function createPluginDefinition() {
|
|
|
2243
2657
|
}
|
|
2244
2658
|
|
|
2245
2659
|
lines.push("</local-memory-plugin>");
|
|
2660
|
+
const contextText = lines.join("\n");
|
|
2661
|
+
if (sessionId) sessionContextCache.set(sessionId, contextText);
|
|
2662
|
+
sessionContextCache.set(ctxKey, contextText);
|
|
2663
|
+
lastSessionTextByProject.set(projectScope, contextText);
|
|
2246
2664
|
lastContextKey = ctxKey;
|
|
2247
|
-
lastContextText =
|
|
2665
|
+
lastContextText = contextText;
|
|
2248
2666
|
if (Array.isArray(event.system)) {
|
|
2249
|
-
event.system.push({ type: "text", text:
|
|
2667
|
+
event.system.push({ type: "text", text: contextText });
|
|
2250
2668
|
}
|
|
2251
2669
|
});
|
|
2252
2670
|
if (ctxReg) registrations.push(ctxReg);
|
|
2253
2671
|
|
|
2254
2672
|
const compReg = await ctx.session.hook("compaction", async function (event) {
|
|
2673
|
+
const explicitSummary = event && typeof event.summary === "string" ? event.summary.trim() : "";
|
|
2674
|
+
if (explicitSummary.length < 40) {
|
|
2675
|
+
return;
|
|
2676
|
+
}
|
|
2255
2677
|
const lastText = extractLastUserText(event.messages);
|
|
2256
2678
|
const slug = lastText
|
|
2257
2679
|
? lastText.toLowerCase().replace(/[^a-z0-9\s]/g, "").trim().split(/\s+/).slice(0, 4).join("-") || "compaction"
|
|
@@ -2259,9 +2681,9 @@ function createPluginDefinition() {
|
|
|
2259
2681
|
const projectDir = (ctx.location && ctx.location.directory) ? ctx.location.directory : "global";
|
|
2260
2682
|
await storeSessionCheckpoint(rootDir, {
|
|
2261
2683
|
slug: slug,
|
|
2262
|
-
title: "
|
|
2684
|
+
title: "Compaction Checkpoint (" + slug + ")",
|
|
2263
2685
|
project: projectDir,
|
|
2264
|
-
summary: "## What was built/fixed/decided\n\
|
|
2686
|
+
summary: "## What was built/fixed/decided\n\n" + explicitSummary
|
|
2265
2687
|
}).catch(function (err) {
|
|
2266
2688
|
console.error("local-memory compaction checkpoint error:", err);
|
|
2267
2689
|
});
|
|
@@ -2269,6 +2691,22 @@ function createPluginDefinition() {
|
|
|
2269
2691
|
if (compReg) registrations.push(compReg);
|
|
2270
2692
|
}
|
|
2271
2693
|
|
|
2694
|
+
const stampFile = path.join(rootDir, ".last-maintain");
|
|
2695
|
+
let shouldMaintain = true;
|
|
2696
|
+
try {
|
|
2697
|
+
if (fs.existsSync(stampFile)) {
|
|
2698
|
+
const ageMs = Date.now() - fs.statSync(stampFile).mtimeMs;
|
|
2699
|
+
shouldMaintain = ageMs > 24 * 60 * 60 * 1000;
|
|
2700
|
+
}
|
|
2701
|
+
} catch {
|
|
2702
|
+
shouldMaintain = false;
|
|
2703
|
+
}
|
|
2704
|
+
if (shouldMaintain && !(options && options.skipAutoMaintain)) {
|
|
2705
|
+
Promise.resolve().then(function () {
|
|
2706
|
+
return maintainMemory(rootDir);
|
|
2707
|
+
}).catch(function () {});
|
|
2708
|
+
}
|
|
2709
|
+
|
|
2272
2710
|
return async function () {
|
|
2273
2711
|
for (const reg of registrations) {
|
|
2274
2712
|
if (reg && typeof reg.dispose === "function") {
|
|
@@ -2284,6 +2722,7 @@ const server = createPluginDefinition();
|
|
|
2284
2722
|
export default server;
|
|
2285
2723
|
export {
|
|
2286
2724
|
server,
|
|
2725
|
+
MemoryRpc,
|
|
2287
2726
|
resolveMemoryDir,
|
|
2288
2727
|
resolveConfigDir,
|
|
2289
2728
|
resolveDbPath,
|
|
@@ -2307,7 +2746,10 @@ export {
|
|
|
2307
2746
|
searchMemory,
|
|
2308
2747
|
storeMemoryFact,
|
|
2309
2748
|
deleteMemoryEntry,
|
|
2310
|
-
|
|
2749
|
+
maintainMemory,
|
|
2750
|
+
storeSessionCheckpoint,
|
|
2751
|
+
readSessionMarkdown,
|
|
2752
|
+
executeMemoryQuery
|
|
2311
2753
|
};
|
|
2312
2754
|
|
|
2313
2755
|
const isDirectRun = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
|
|
@@ -2399,6 +2841,29 @@ if (isDirectRun) {
|
|
|
2399
2841
|
console.error("Store failed:", err);
|
|
2400
2842
|
process.exit(1);
|
|
2401
2843
|
});
|
|
2844
|
+
} else if (cmd === "store-json") {
|
|
2845
|
+
const payloadIdx = process.argv.indexOf("--payload");
|
|
2846
|
+
const rawPayload = (payloadIdx !== -1 && process.argv[payloadIdx + 1]) ? process.argv[payloadIdx + 1] : "{}";
|
|
2847
|
+
const parsedPayload = JSON.parse(rawPayload);
|
|
2848
|
+
storeMemoryFact(rootDir, parsedPayload).then(function (entry) {
|
|
2849
|
+
const out = Object.assign({}, entry);
|
|
2850
|
+
delete out.vector;
|
|
2851
|
+
delete out._haystack;
|
|
2852
|
+
console.log(JSON.stringify(out));
|
|
2853
|
+
}).catch(function (err) {
|
|
2854
|
+
console.error("Store JSON failed:", err);
|
|
2855
|
+
process.exit(1);
|
|
2856
|
+
});
|
|
2857
|
+
} else if (cmd === "delete-json") {
|
|
2858
|
+
const payloadIdx = process.argv.indexOf("--payload");
|
|
2859
|
+
const rawPayload = (payloadIdx !== -1 && process.argv[payloadIdx + 1]) ? process.argv[payloadIdx + 1] : "{}";
|
|
2860
|
+
const parsedPayload = JSON.parse(rawPayload);
|
|
2861
|
+
deleteMemoryEntry(rootDir, parsedPayload.id).then(function (res) {
|
|
2862
|
+
console.log(JSON.stringify(res));
|
|
2863
|
+
}).catch(function (err) {
|
|
2864
|
+
console.error("Delete JSON failed:", err);
|
|
2865
|
+
process.exit(1);
|
|
2866
|
+
});
|
|
2402
2867
|
} else if (cmd === "delete" || cmd === "rm") {
|
|
2403
2868
|
const id = process.argv.slice(3).join(",");
|
|
2404
2869
|
deleteMemoryEntry(rootDir, id).then(function (res) {
|
|
@@ -2407,5 +2872,13 @@ if (isDirectRun) {
|
|
|
2407
2872
|
console.error("Delete failed:", err);
|
|
2408
2873
|
process.exit(1);
|
|
2409
2874
|
});
|
|
2875
|
+
} else if (cmd === "maintain" || cmd === "clean") {
|
|
2876
|
+
const pruneImported = process.argv.includes("--prune-imported");
|
|
2877
|
+
maintainMemory(rootDir, { pruneImportedRules: pruneImported }).then(function (res) {
|
|
2878
|
+
console.log("Memory maintenance complete: removed " + res.deletedCount + " duplicate/stub entries; " + res.total + " active entries synced.");
|
|
2879
|
+
}).catch(function (err) {
|
|
2880
|
+
console.error("Maintain failed:", err);
|
|
2881
|
+
process.exit(1);
|
|
2882
|
+
});
|
|
2410
2883
|
}
|
|
2411
2884
|
}
|