@oyasmi/pipiclaw 0.9.6-beta.2 → 0.9.6-beta.3
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.en.md +2 -2
- package/README.md +2 -2
- package/dist/agent/channel-runner.js +2 -0
- package/dist/agent/maintenance-context.js +21 -2
- package/dist/agent/turn/turn-context.js +10 -6
- package/dist/config/settings.d.ts +0 -2
- package/dist/config/settings.js +0 -2
- package/dist/config/tools.d.ts +8 -2
- package/dist/config/tools.js +35 -19
- package/dist/memory/anchors.d.ts +5 -0
- package/dist/memory/anchors.js +49 -0
- package/dist/memory/boundary-work.d.ts +1 -0
- package/dist/memory/boundary-work.js +1 -0
- package/dist/memory/commands.js +23 -6
- package/dist/memory/index-budget.d.ts +16 -0
- package/dist/memory/index-budget.js +24 -2
- package/dist/memory/journal.d.ts +7 -12
- package/dist/memory/journal.js +9 -41
- package/dist/memory/lifecycle.d.ts +1 -0
- package/dist/memory/lifecycle.js +2 -0
- package/dist/memory/reflect-job.d.ts +1 -0
- package/dist/memory/reflect-job.js +1 -0
- package/dist/memory/reflect.d.ts +10 -0
- package/dist/memory/reflect.js +103 -20
- package/dist/memory/render.d.ts +4 -1
- package/dist/memory/render.js +6 -4
- package/dist/memory/review-log.d.ts +2 -2
- package/dist/memory/scheduler.d.ts +7 -0
- package/dist/memory/scheduler.js +70 -3
- package/dist/memory/search-index-db.d.ts +15 -0
- package/dist/memory/search-index-db.js +247 -0
- package/dist/memory/search-index-files.d.ts +11 -0
- package/dist/memory/search-index-files.js +26 -0
- package/dist/memory/search-index-notes.d.ts +11 -0
- package/dist/memory/search-index-notes.js +155 -0
- package/dist/memory/search-index-sync.d.ts +19 -0
- package/dist/memory/search-index-sync.js +267 -0
- package/dist/memory/search-terms.d.ts +12 -0
- package/dist/memory/search-terms.js +185 -0
- package/dist/memory/search.d.ts +8 -28
- package/dist/memory/search.js +18 -278
- package/dist/memory/session-corpus.d.ts +15 -26
- package/dist/memory/session-corpus.js +120 -327
- package/dist/memory/session-search.d.ts +5 -3
- package/dist/memory/session-search.js +119 -171
- package/dist/memory/sidecar-worker.d.ts +2 -0
- package/dist/memory/sidecar-worker.js +25 -1
- package/dist/memory/store.d.ts +4 -0
- package/dist/memory/store.js +22 -1
- package/dist/memory/task-archive-digest.d.ts +61 -0
- package/dist/memory/task-archive-digest.js +366 -0
- package/dist/models/provider-login.d.ts +1 -1
- package/dist/models/provider-login.js +1 -1
- package/dist/playbooks/memory-operations.md +2 -2
- package/dist/shared/text-utils.d.ts +0 -1
- package/dist/shared/text-utils.js +0 -1
- package/dist/subagents/runs.d.ts +1 -1
- package/dist/subagents/task-envelope.js +6 -8
- package/dist/tools/memory-manage.d.ts +1 -0
- package/dist/tools/memory-manage.js +9 -23
- package/dist/tools/registry.js +2 -0
- package/dist/tools/session-search.d.ts +1 -0
- package/dist/tools/session-search.js +12 -6
- package/dist/tools/web-search.d.ts +13 -7
- package/dist/tools/web-search.js +62 -19
- package/dist/web/client.d.ts +2 -0
- package/dist/web/client.js +7 -3
- package/dist/web/config.d.ts +17 -4
- package/dist/web/config.js +42 -4
- package/dist/web/format.d.ts +2 -1
- package/dist/web/format.js +7 -3
- package/dist/web/search-providers.d.ts +15 -8
- package/dist/web/search-providers.js +208 -139
- package/dist/web/search.d.ts +13 -3
- package/dist/web/search.js +86 -40
- package/package.json +1 -1
- package/dist/memory/chinese-words.d.ts +0 -1
- package/dist/memory/chinese-words.js +0 -273
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { open } from "node:fs/promises";
|
|
3
|
+
import { setImmediate as yieldToLoop } from "node:timers/promises";
|
|
4
|
+
import { DESK_DIR_PREFIX, isDeskEntry, isDeskName } from "../desk/paths.js";
|
|
5
|
+
import * as log from "../log.js";
|
|
6
|
+
import { parseLocalTime } from "../shared/local-time.js";
|
|
7
|
+
import { isNodeError, readOptionalTextFile } from "../shared/os.js";
|
|
8
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
9
|
+
import { getSearchIndexDir, getSearchIndexPath, removeSearchIndex, transaction, withSearchIndex, } from "./search-index-db.js";
|
|
10
|
+
import { listIndexSourceEntries, sameIndexSourceStat, statIndexSource } from "./search-index-files.js";
|
|
11
|
+
import { searchTextFor } from "./search-terms.js";
|
|
12
|
+
import { archivedTaskDoc, dedupKey, listDeskTranscriptSources, parseJsonLine, parseTranscriptLine, } from "./session-corpus.js";
|
|
13
|
+
const HEAD_BYTES = 4096;
|
|
14
|
+
const SLICE_ROWS = 1_000;
|
|
15
|
+
const SLICE_BYTES = 256 * 1024;
|
|
16
|
+
// Leave room for SQLite commit and the final row (individual transcript lines vary in size).
|
|
17
|
+
const SLICE_WORK_MS = 12;
|
|
18
|
+
function sha1(value) {
|
|
19
|
+
return createHash("sha1").update(value).digest("hex");
|
|
20
|
+
}
|
|
21
|
+
function makeWriter(db) {
|
|
22
|
+
const listFiles = db.prepare("SELECT * FROM files WHERE kind IN ('session', 'log', 'task')");
|
|
23
|
+
const upsertFile = db.prepare(`
|
|
24
|
+
INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
25
|
+
ON CONFLICT(path) DO UPDATE SET kind=excluded.kind, conversation=excluded.conversation,
|
|
26
|
+
ino=excluded.ino, size=excluded.size, mtime_ms=excluded.mtime_ms, indexed_bytes=excluded.indexed_bytes,
|
|
27
|
+
indexed_lines=excluded.indexed_lines, head_len=excluded.head_len, head_hash=excluded.head_hash
|
|
28
|
+
`);
|
|
29
|
+
const deleteFile = db.prepare("DELETE FROM files WHERE path = ?");
|
|
30
|
+
const readDocId = db.prepare("SELECT id FROM docs WHERE hash = ?");
|
|
31
|
+
const insertDoc = db.prepare(`
|
|
32
|
+
INSERT INTO docs(hash, role, text, search_text, truncated) VALUES (?, ?, ?, ?, ?)
|
|
33
|
+
ON CONFLICT(hash) DO NOTHING
|
|
34
|
+
`);
|
|
35
|
+
const oldDocIds = db.prepare("SELECT DISTINCT doc_id FROM refs WHERE path = ?");
|
|
36
|
+
const deleteRefs = db.prepare("DELETE FROM refs WHERE path = ?");
|
|
37
|
+
// We only insert beyond committed progress or after removing all refs for a rebuilt file.
|
|
38
|
+
const insertRef = db.prepare("INSERT INTO refs VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
|
|
39
|
+
const orphanStatements = new Map();
|
|
40
|
+
return {
|
|
41
|
+
files: () => listFiles.all(),
|
|
42
|
+
progress(source, state) {
|
|
43
|
+
upsertFile.run(state.path, source.kind, source.conversation ?? null, state.ino, state.size, state.mtime_ms, state.indexed_bytes, state.indexed_lines, state.head_len, state.head_hash);
|
|
44
|
+
},
|
|
45
|
+
remove(path) {
|
|
46
|
+
const ids = oldDocIds.all(path).map(({ doc_id }) => Number(doc_id));
|
|
47
|
+
deleteRefs.run(path);
|
|
48
|
+
deleteFile.run(path);
|
|
49
|
+
for (let i = 0; i < ids.length; i += 500) {
|
|
50
|
+
const batch = ids.slice(i, i + 500);
|
|
51
|
+
let statement = orphanStatements.get(batch.length);
|
|
52
|
+
if (!statement) {
|
|
53
|
+
statement = db.prepare(`DELETE FROM docs WHERE id IN (${batch.map(() => "?").join(",")})
|
|
54
|
+
AND NOT EXISTS (SELECT 1 FROM refs WHERE refs.doc_id = docs.id)`);
|
|
55
|
+
orphanStatements.set(batch.length, statement);
|
|
56
|
+
}
|
|
57
|
+
statement.run(...batch);
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
add(source, line, doc) {
|
|
61
|
+
const hash = sha1(`${doc.role}\0${dedupKey(doc.text)}`);
|
|
62
|
+
const existing = readDocId.get(hash);
|
|
63
|
+
const inserted = existing
|
|
64
|
+
? undefined
|
|
65
|
+
: insertDoc.run(hash, doc.role, doc.text, searchTextFor(doc.text), Number(doc.truncated));
|
|
66
|
+
const id = existing?.id ?? (inserted?.changes ? inserted.lastInsertRowid : readDocId.get(hash)?.id);
|
|
67
|
+
insertRef.run(source.relPath, line, Number(id), source.source, source.conversation ?? null, doc.speaker ?? null, doc.ts ?? null, doc.ts ? (parseLocalTime(doc.ts) ?? null) : null);
|
|
68
|
+
return inserted?.changes ? 1 : 0;
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function measureTransaction(db, stats, work) {
|
|
73
|
+
const started = performance.now();
|
|
74
|
+
transaction(db, () => work(started));
|
|
75
|
+
stats.maxSliceMs = Math.max(stats.maxSliceMs, performance.now() - started);
|
|
76
|
+
}
|
|
77
|
+
async function readRange(file, start, end) {
|
|
78
|
+
const buffer = Buffer.allocUnsafe(end - start);
|
|
79
|
+
let offset = 0;
|
|
80
|
+
while (offset < buffer.length) {
|
|
81
|
+
const { bytesRead } = await file.read(buffer, offset, buffer.length - offset, start + offset);
|
|
82
|
+
if (bytesRead === 0)
|
|
83
|
+
break;
|
|
84
|
+
offset += bytesRead;
|
|
85
|
+
}
|
|
86
|
+
return buffer.subarray(0, offset);
|
|
87
|
+
}
|
|
88
|
+
async function syncJsonl(db, writer, source, previous, stats, listed) {
|
|
89
|
+
if (previous && previous.indexed_bytes === listed.size && sameIndexSourceStat(previous, listed))
|
|
90
|
+
return;
|
|
91
|
+
const file = await open(source.path, "r");
|
|
92
|
+
try {
|
|
93
|
+
const current = await file.stat();
|
|
94
|
+
const head = await readRange(file, 0, Math.min(HEAD_BYTES, current.size));
|
|
95
|
+
const replaced = previous &&
|
|
96
|
+
((previous.ino !== 0 && current.ino !== 0 && previous.ino !== current.ino) ||
|
|
97
|
+
current.size < previous.size ||
|
|
98
|
+
(current.size === previous.size && current.mtimeMs !== previous.mtime_ms) ||
|
|
99
|
+
sha1(head.subarray(0, previous.head_len)) !== previous.head_hash);
|
|
100
|
+
const state = {
|
|
101
|
+
path: source.relPath,
|
|
102
|
+
ino: current.ino,
|
|
103
|
+
size: current.size,
|
|
104
|
+
mtime_ms: current.mtimeMs,
|
|
105
|
+
indexed_bytes: replaced ? 0 : (previous?.indexed_bytes ?? 0),
|
|
106
|
+
indexed_lines: replaced ? 0 : (previous?.indexed_lines ?? 0),
|
|
107
|
+
head_len: head.length,
|
|
108
|
+
head_hash: sha1(head),
|
|
109
|
+
};
|
|
110
|
+
const data = await readRange(file, state.indexed_bytes, current.size);
|
|
111
|
+
// A truncation during the read must not commit progress for a snapshot that vanished.
|
|
112
|
+
if (data.length !== current.size - state.indexed_bytes || head.length !== Math.min(HEAD_BYTES, current.size))
|
|
113
|
+
return;
|
|
114
|
+
const consumed = data.lastIndexOf(0x0a) + 1;
|
|
115
|
+
if (!consumed && previous && !replaced)
|
|
116
|
+
return;
|
|
117
|
+
let cursor = 0;
|
|
118
|
+
do {
|
|
119
|
+
measureTransaction(db, stats, (started) => {
|
|
120
|
+
if (cursor === 0 && replaced)
|
|
121
|
+
writer.remove(source.relPath);
|
|
122
|
+
let rows = 0;
|
|
123
|
+
const sliceStart = cursor;
|
|
124
|
+
while (cursor < consumed) {
|
|
125
|
+
const end = data.indexOf(0x0a, cursor);
|
|
126
|
+
const doc = parseTranscriptLine(source.source, parseJsonLine(data.toString("utf8", cursor, end)));
|
|
127
|
+
state.indexed_lines++;
|
|
128
|
+
if (doc)
|
|
129
|
+
stats.docsAdded += writer.add(source, state.indexed_lines, doc);
|
|
130
|
+
state.indexed_bytes += end + 1 - cursor;
|
|
131
|
+
cursor = end + 1;
|
|
132
|
+
if (++rows >= SLICE_ROWS ||
|
|
133
|
+
cursor - sliceStart >= SLICE_BYTES ||
|
|
134
|
+
performance.now() - started >= SLICE_WORK_MS)
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
writer.progress(source, state);
|
|
138
|
+
});
|
|
139
|
+
await yieldToLoop();
|
|
140
|
+
} while (cursor < consumed);
|
|
141
|
+
if (replaced)
|
|
142
|
+
stats.filesRebuilt++;
|
|
143
|
+
else if (previous)
|
|
144
|
+
stats.filesAppended++;
|
|
145
|
+
else
|
|
146
|
+
stats.filesIndexed++;
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
await file.close();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async function syncTask(db, writer, source, previous, stats, md) {
|
|
153
|
+
const jsonlPath = source.path.replace(/\.md$/, ".jsonl");
|
|
154
|
+
const jsonl = await statIndexSource(jsonlPath);
|
|
155
|
+
const mtimeMs = Math.max(md.mtimeMs, jsonl?.mtimeMs ?? 0);
|
|
156
|
+
const size = md.size + (jsonl?.size ?? 0);
|
|
157
|
+
// Keep each member's fingerprint: max mtime and total bytes alone can hide a replaced sibling.
|
|
158
|
+
const fingerprint = sha1(JSON.stringify([md.ino, md.mtimeMs, md.size, jsonl?.ino, jsonl?.mtimeMs, jsonl?.size]));
|
|
159
|
+
if (previous?.head_hash === fingerprint)
|
|
160
|
+
return;
|
|
161
|
+
const [markdown, notes] = await Promise.all([
|
|
162
|
+
readOptionalTextFile(source.path),
|
|
163
|
+
jsonl ? readOptionalTextFile(jsonlPath) : "",
|
|
164
|
+
]);
|
|
165
|
+
const doc = archivedTaskDoc(source.path, markdown, notes, md.mtimeMs);
|
|
166
|
+
measureTransaction(db, stats, () => {
|
|
167
|
+
if (previous)
|
|
168
|
+
writer.remove(source.relPath);
|
|
169
|
+
if (doc)
|
|
170
|
+
stats.docsAdded += writer.add(source, 0, doc);
|
|
171
|
+
writer.progress(source, {
|
|
172
|
+
path: source.relPath,
|
|
173
|
+
ino: md.ino,
|
|
174
|
+
size,
|
|
175
|
+
mtime_ms: mtimeMs,
|
|
176
|
+
indexed_bytes: size,
|
|
177
|
+
indexed_lines: 0,
|
|
178
|
+
head_len: 0,
|
|
179
|
+
head_hash: fingerprint,
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
await yieldToLoop();
|
|
183
|
+
if (previous)
|
|
184
|
+
stats.filesRebuilt++;
|
|
185
|
+
else
|
|
186
|
+
stats.filesIndexed++;
|
|
187
|
+
}
|
|
188
|
+
export async function syncTranscriptSources(handle, deskDir) {
|
|
189
|
+
const started = performance.now();
|
|
190
|
+
const db = handle.db;
|
|
191
|
+
const writer = makeWriter(db);
|
|
192
|
+
const sources = await listDeskTranscriptSources(deskDir);
|
|
193
|
+
const previous = new Map(writer.files().map((state) => [state.path, state]));
|
|
194
|
+
const stats = {
|
|
195
|
+
filesScanned: sources.length,
|
|
196
|
+
filesIndexed: 0,
|
|
197
|
+
filesAppended: 0,
|
|
198
|
+
filesRebuilt: 0,
|
|
199
|
+
filesRemoved: 0,
|
|
200
|
+
docsAdded: 0,
|
|
201
|
+
durationMs: 0,
|
|
202
|
+
maxSliceMs: 0,
|
|
203
|
+
};
|
|
204
|
+
// Batch metadata reads while keeping SQLite writes serialized and bounding outstanding I/O.
|
|
205
|
+
for (let i = 0; i < sources.length; i += 64) {
|
|
206
|
+
const batch = sources.slice(i, i + 64);
|
|
207
|
+
const metadata = await Promise.allSettled(batch.map((source) => statIndexSource(source.path)));
|
|
208
|
+
for (const [index, source] of batch.entries()) {
|
|
209
|
+
const state = previous.get(source.relPath);
|
|
210
|
+
previous.delete(source.relPath);
|
|
211
|
+
const result = metadata[index];
|
|
212
|
+
try {
|
|
213
|
+
if (result.status === "rejected")
|
|
214
|
+
throw result.reason;
|
|
215
|
+
if (!result.value) {
|
|
216
|
+
if (state)
|
|
217
|
+
previous.set(source.relPath, state);
|
|
218
|
+
}
|
|
219
|
+
else if (source.kind === "task") {
|
|
220
|
+
await syncTask(db, writer, source, state, stats, result.value);
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
await syncJsonl(db, writer, source, state, stats, result.value);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
// Handle source I/O independently. SQLite faults must reach the connection's recovery loop.
|
|
228
|
+
if (!isNodeError(error) || error.code?.startsWith("ERR_SQLITE"))
|
|
229
|
+
throw error;
|
|
230
|
+
if (error.code === "ENOENT" && state)
|
|
231
|
+
previous.set(source.relPath, state);
|
|
232
|
+
else if (error.code !== "ENOENT") {
|
|
233
|
+
log.logWarn("memory.search_index.sync_failed", "Search index sync failed", {
|
|
234
|
+
reason: errorMessage(error),
|
|
235
|
+
fields: { path: source.path },
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
for (const path of previous.keys()) {
|
|
242
|
+
measureTransaction(db, stats, () => writer.remove(path));
|
|
243
|
+
stats.filesRemoved++;
|
|
244
|
+
await yieldToLoop();
|
|
245
|
+
}
|
|
246
|
+
stats.durationMs = performance.now() - started;
|
|
247
|
+
return stats;
|
|
248
|
+
}
|
|
249
|
+
export function syncDeskSearchIndex(target) {
|
|
250
|
+
return withSearchIndex(getSearchIndexPath(target.appHomeDir, target.desk), (handle) => syncTranscriptSources(handle, target.deskDir));
|
|
251
|
+
}
|
|
252
|
+
export async function pruneOrphanSearchIndexes(appHomeDir, workspaceDir) {
|
|
253
|
+
const indexDir = getSearchIndexDir(appHomeDir);
|
|
254
|
+
const [indexes, entries] = await Promise.all([
|
|
255
|
+
listIndexSourceEntries(indexDir),
|
|
256
|
+
listIndexSourceEntries(workspaceDir),
|
|
257
|
+
]);
|
|
258
|
+
const desks = new Set(entries.filter(isDeskEntry).map((entry) => entry.name));
|
|
259
|
+
const orphans = new Set();
|
|
260
|
+
for (const entry of indexes) {
|
|
261
|
+
const desk = /^(.+)\.sqlite(?:-wal|-shm)?$/.exec(entry.name)?.[1];
|
|
262
|
+
if (desk && isDeskName(desk) && !desks.has(`${DESK_DIR_PREFIX}${desk}`))
|
|
263
|
+
orphans.add(desk);
|
|
264
|
+
}
|
|
265
|
+
await Promise.all([...orphans].map((desk) => removeSearchIndex(getSearchIndexPath(appHomeDir, desk))));
|
|
266
|
+
return [...orphans];
|
|
267
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare function searchTextFor(text: string): string | null;
|
|
2
|
+
export interface QueryTerms {
|
|
3
|
+
latin: string[];
|
|
4
|
+
cjk: string[];
|
|
5
|
+
}
|
|
6
|
+
export declare function buildQueryTerms(query: string): QueryTerms;
|
|
7
|
+
export declare function buildMatchExpression(terms: QueryTerms): string | null;
|
|
8
|
+
export declare function matchedTerms(text: string, terms: QueryTerms): QueryTerms;
|
|
9
|
+
export declare function effectiveTermCount(terms: QueryTerms): number;
|
|
10
|
+
export declare function countMatchedUnits(text: string, terms: QueryTerms): number;
|
|
11
|
+
export declare function enoughMatches(units: number, effective: number): boolean;
|
|
12
|
+
export declare function windowAroundDensestMatch(text: string, matches: string[], limit: number, omission?: string): string;
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
const LATIN_STOP_WORDS = new Set([
|
|
2
|
+
"a",
|
|
3
|
+
"an",
|
|
4
|
+
"and",
|
|
5
|
+
"are",
|
|
6
|
+
"as",
|
|
7
|
+
"at",
|
|
8
|
+
"be",
|
|
9
|
+
"been",
|
|
10
|
+
"being",
|
|
11
|
+
"by",
|
|
12
|
+
"can",
|
|
13
|
+
"could",
|
|
14
|
+
"did",
|
|
15
|
+
"do",
|
|
16
|
+
"does",
|
|
17
|
+
"doing",
|
|
18
|
+
"for",
|
|
19
|
+
"from",
|
|
20
|
+
"had",
|
|
21
|
+
"has",
|
|
22
|
+
"have",
|
|
23
|
+
"here",
|
|
24
|
+
"how",
|
|
25
|
+
"i",
|
|
26
|
+
"in",
|
|
27
|
+
"is",
|
|
28
|
+
"it",
|
|
29
|
+
"its",
|
|
30
|
+
"me",
|
|
31
|
+
"my",
|
|
32
|
+
"of",
|
|
33
|
+
"on",
|
|
34
|
+
"or",
|
|
35
|
+
"our",
|
|
36
|
+
"please",
|
|
37
|
+
"should",
|
|
38
|
+
"that",
|
|
39
|
+
"the",
|
|
40
|
+
"their",
|
|
41
|
+
"them",
|
|
42
|
+
"there",
|
|
43
|
+
"these",
|
|
44
|
+
"they",
|
|
45
|
+
"this",
|
|
46
|
+
"to",
|
|
47
|
+
"was",
|
|
48
|
+
"we",
|
|
49
|
+
"were",
|
|
50
|
+
"what",
|
|
51
|
+
"when",
|
|
52
|
+
"where",
|
|
53
|
+
"which",
|
|
54
|
+
"who",
|
|
55
|
+
"why",
|
|
56
|
+
"with",
|
|
57
|
+
"would",
|
|
58
|
+
"you",
|
|
59
|
+
"your",
|
|
60
|
+
]);
|
|
61
|
+
const SEARCH_MARK = "\u200b";
|
|
62
|
+
const CJK = String.raw `\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\u30fc\uff70\uff9e\uff9f`;
|
|
63
|
+
const HAS_CJK = new RegExp(`[${CJK}]`, "u");
|
|
64
|
+
const CJK_BOUNDARY = new RegExp(`(?<=[${CJK}])(?=[\\p{L}\\p{N}${CJK}])|(?<=[\\p{L}\\p{N}${CJK}])(?=[${CJK}])`, "gu");
|
|
65
|
+
const CJK_RUN = new RegExp(`([${CJK}]+)`, "gu");
|
|
66
|
+
const LATIN_PART = /[\p{L}\p{N}]+(?:[-./_:]+[\p{L}\p{N}]+)*/gu;
|
|
67
|
+
const CJK_STOP_WORDS = new RegExp(("我们 你们 他们 这个 那个 一下 一个 可以 时候 现在 知道 告诉 记得 还是 就是 不是 没有 已经 因为 所以 但是 如果 然后 还有 请问 帮我 怎么 怎样 如何 为什么 什么 是否 哪里 哪个 哪些 应该 一些 上次 之前 刚才 刚刚 那次 问题 " +
|
|
68
|
+
"的 了 是 吗 呢 吧 啊 呀 哦 嗯 么 在 和 与 也 都 就 还 又 把 被")
|
|
69
|
+
.split(" ")
|
|
70
|
+
.sort((a, b) => b.length - a.length)
|
|
71
|
+
.join("|"), "gu");
|
|
72
|
+
export function searchTextFor(text) {
|
|
73
|
+
return HAS_CJK.test(text) ? text.replace(CJK_BOUNDARY, SEARCH_MARK) : null;
|
|
74
|
+
}
|
|
75
|
+
function stripSearchMarks(text) {
|
|
76
|
+
return text.replaceAll(SEARCH_MARK, "");
|
|
77
|
+
}
|
|
78
|
+
export function buildQueryTerms(query) {
|
|
79
|
+
const latin = new Set();
|
|
80
|
+
const cjk = new Set();
|
|
81
|
+
for (const [index, part] of query.toLowerCase().split(CJK_RUN).entries()) {
|
|
82
|
+
if (index % 2 === 0) {
|
|
83
|
+
for (const word of part.matchAll(LATIN_PART)) {
|
|
84
|
+
if (latin.size >= 16)
|
|
85
|
+
break;
|
|
86
|
+
if (word[0].length >= 2 && !LATIN_STOP_WORDS.has(word[0]))
|
|
87
|
+
latin.add(word[0]);
|
|
88
|
+
}
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
for (const fragment of part.split(CJK_STOP_WORDS)) {
|
|
92
|
+
if (cjk.size >= 24)
|
|
93
|
+
break;
|
|
94
|
+
const chars = [...fragment];
|
|
95
|
+
if (chars.length === 1)
|
|
96
|
+
cjk.add(chars[0]);
|
|
97
|
+
for (let i = 1; i < chars.length && cjk.size < 24; i++) {
|
|
98
|
+
cjk.add(chars[i - 1] + chars[i]);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return { latin: [...latin], cjk: [...cjk] };
|
|
103
|
+
}
|
|
104
|
+
function isPrefixTerm(word) {
|
|
105
|
+
return word.length >= 4 && /(?:^|[-./:])[a-z0-9_]+$/.test(word);
|
|
106
|
+
}
|
|
107
|
+
function quote(word) {
|
|
108
|
+
return `"${word.replaceAll('"', "")}"`;
|
|
109
|
+
}
|
|
110
|
+
export function buildMatchExpression(terms) {
|
|
111
|
+
return ([
|
|
112
|
+
...terms.latin.map((word) => quote(word) + (isPrefixTerm(word) ? "*" : "")),
|
|
113
|
+
...terms.cjk.map((word) => quote([...word].join(" "))),
|
|
114
|
+
].join(" OR ") || null);
|
|
115
|
+
}
|
|
116
|
+
export function matchedTerms(text, terms) {
|
|
117
|
+
const lower = stripSearchMarks(text).toLowerCase();
|
|
118
|
+
return {
|
|
119
|
+
latin: terms.latin.filter((word) => {
|
|
120
|
+
if (!isPrefixTerm(word))
|
|
121
|
+
return lower.includes(word);
|
|
122
|
+
// CJK boundaries are token boundaries too, even though both sides can be letters.
|
|
123
|
+
const literal = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
124
|
+
return new RegExp(`(?<![\\p{L}\\p{N}])${literal}|(?<=[${CJK}])${literal}`, "u").test(lower);
|
|
125
|
+
}),
|
|
126
|
+
cjk: terms.cjk.filter((word) => lower.includes(word)),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
export function effectiveTermCount(terms) {
|
|
130
|
+
return terms.latin.length + Math.ceil(terms.cjk.length / 2);
|
|
131
|
+
}
|
|
132
|
+
export function countMatchedUnits(text, terms) {
|
|
133
|
+
return effectiveTermCount(matchedTerms(text, terms));
|
|
134
|
+
}
|
|
135
|
+
export function enoughMatches(units, effective) {
|
|
136
|
+
return effective < 5 || units >= 2;
|
|
137
|
+
}
|
|
138
|
+
export function windowAroundDensestMatch(text, matches, limit, omission = "[...]") {
|
|
139
|
+
if (text.length <= limit)
|
|
140
|
+
return text;
|
|
141
|
+
const inline = omission === "…";
|
|
142
|
+
const maxChars = Math.max(1, limit - (inline ? 2 * omission.length : 0));
|
|
143
|
+
const lower = text.toLowerCase();
|
|
144
|
+
const cursors = matches.map((word) => ({ word, offset: lower.indexOf(word) })).filter((item) => item.offset >= 0);
|
|
145
|
+
const positions = [];
|
|
146
|
+
// Take occurrences in rounds so a frequently repeated word cannot exhaust the whole budget.
|
|
147
|
+
while (cursors.length && positions.length < 400) {
|
|
148
|
+
for (let i = cursors.length - 1; i >= 0 && positions.length < 400; i--) {
|
|
149
|
+
const { word, offset } = cursors[i];
|
|
150
|
+
positions.push({ word, offset });
|
|
151
|
+
const next = lower.indexOf(word, offset + 1);
|
|
152
|
+
if (next < 0)
|
|
153
|
+
cursors.splice(i, 1);
|
|
154
|
+
else
|
|
155
|
+
cursors[i].offset = next;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
positions.sort((a, b) => a.offset - b.offset || a.word.length - b.word.length);
|
|
159
|
+
const counts = new Map();
|
|
160
|
+
let left = 0;
|
|
161
|
+
let bestCount = 0;
|
|
162
|
+
let bestStart = 0;
|
|
163
|
+
let bestEnd = 0;
|
|
164
|
+
for (const { word, offset } of positions) {
|
|
165
|
+
const end = offset + Math.min(word.length, maxChars);
|
|
166
|
+
counts.set(word, (counts.get(word) ?? 0) + 1);
|
|
167
|
+
while (end - positions[left].offset > maxChars) {
|
|
168
|
+
const leaving = positions[left++].word;
|
|
169
|
+
const count = (counts.get(leaving) ?? 1) - 1;
|
|
170
|
+
if (count)
|
|
171
|
+
counts.set(leaving, count);
|
|
172
|
+
else
|
|
173
|
+
counts.delete(leaving);
|
|
174
|
+
}
|
|
175
|
+
if (counts.size > bestCount) {
|
|
176
|
+
bestCount = counts.size;
|
|
177
|
+
bestStart = positions[left].offset;
|
|
178
|
+
bestEnd = end;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const start = Math.min(text.length - maxChars, Math.max(0, Math.floor((bestStart + bestEnd - maxChars) / 2)));
|
|
182
|
+
const end = start + maxChars;
|
|
183
|
+
const separator = inline ? "" : "\n";
|
|
184
|
+
return `${start > 0 ? omission + separator : ""}${text.slice(start, end)}${end < text.length ? separator + omission : ""}`;
|
|
185
|
+
}
|
package/dist/memory/search.d.ts
CHANGED
|
@@ -1,35 +1,15 @@
|
|
|
1
|
+
import { type MemorySearchHit } from "./search-index-notes.js";
|
|
1
2
|
import type { MemoryEntry } from "./store.js";
|
|
2
|
-
/**
|
|
3
|
-
* Age-bucketed recency boost (≤1 day / ≤7 days / ≤30 days / older), scaled by `weights`. Kept
|
|
4
|
-
* here (not `session-search.ts`) so both cold-storage callers share one scoring primitive; each
|
|
5
|
-
* caller supplies its own weights since the two scoring systems live on different magnitudes.
|
|
6
|
-
*/
|
|
7
|
-
export declare function recencyBoostByAge(timestamp: string | undefined, weights: {
|
|
8
|
-
day: number;
|
|
9
|
-
week: number;
|
|
10
|
-
month: number;
|
|
11
|
-
}): number;
|
|
12
|
-
export declare function tokenizeRecallText(text: string): string[];
|
|
13
|
-
export declare const NEAR_DUPLICATE_JACCARD = 0.6;
|
|
14
3
|
export declare function descriptionSimilarity(a: string, b: string): number;
|
|
15
4
|
/** Entries whose description is a near-duplicate of `description`, strongest match first. */
|
|
16
5
|
export declare function findNearDuplicateEntries(description: string, entries: MemoryEntry[]): MemoryEntry[];
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
line: string;
|
|
23
|
-
}
|
|
24
|
-
export interface MemorySearchInput {
|
|
6
|
+
interface MemorySearchInput {
|
|
7
|
+
appHomeDir: string;
|
|
8
|
+
desk: string;
|
|
9
|
+
deskDir: string;
|
|
10
|
+
workspaceDir: string;
|
|
25
11
|
query: string;
|
|
26
|
-
entries: MemoryEntry[];
|
|
27
|
-
/** `{ date, content }` per journal file, newest first. */
|
|
28
|
-
journal?: Array<{
|
|
29
|
-
date: string;
|
|
30
|
-
content: string;
|
|
31
|
-
}>;
|
|
32
|
-
workspaceMemory?: string;
|
|
33
12
|
limit?: number;
|
|
34
13
|
}
|
|
35
|
-
export declare function searchMemory(input: MemorySearchInput): MemorySearchHit[]
|
|
14
|
+
export declare function searchMemory(input: MemorySearchInput): Promise<MemorySearchHit[]>;
|
|
15
|
+
export {};
|