@operad-io/memory 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +16 -2
- package/memory.schema.json +17 -0
- package/package.json +23 -4
- package/skills/memory/SKILL.md +84 -0
- package/src/commit.ts +279 -0
- package/src/index.ts +138 -0
- package/src/link-report.ts +224 -0
- package/src/links.ts +378 -0
- package/src/memory.ts +215 -0
- package/src/search/backend.ts +489 -0
- package/src/search/chunks.ts +86 -0
- package/src/search/command.ts +216 -0
- package/src/search/frontmatter.ts +114 -0
- package/src/search/service.ts +580 -0
- package/src/search/sources.ts +212 -0
- package/src/search/types.ts +245 -0
- package/src/tidy.ts +342 -0
- package/src/wiki.ts +619 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `memory search` and `memory read`: the verbs behind the operad tools a bot
|
|
3
|
+
* gets. Both refresh the index first, so a file another process wrote and a
|
|
4
|
+
* chat that just gained a message are found without a watcher having to catch
|
|
5
|
+
* up. A caller may give the arguments as JSON on stdin (the MCP tools do) or as
|
|
6
|
+
* words on the command line.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { isRecord, type CommandContext } from "@operad-io/engine";
|
|
10
|
+
import {
|
|
11
|
+
fieldFiltersOf,
|
|
12
|
+
openMemorySearch,
|
|
13
|
+
requestedLimit,
|
|
14
|
+
requestedScopes,
|
|
15
|
+
} from "./service.ts";
|
|
16
|
+
import {
|
|
17
|
+
SEARCH_SCOPES,
|
|
18
|
+
SearchError,
|
|
19
|
+
type Backlink,
|
|
20
|
+
type ReadResult,
|
|
21
|
+
type SearchScope,
|
|
22
|
+
} from "./types.ts";
|
|
23
|
+
|
|
24
|
+
function textOf(value: unknown, name: string): string {
|
|
25
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
26
|
+
throw new SearchError(`${name} must be text`);
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function scopesOf(value: unknown): readonly SearchScope[] | undefined {
|
|
32
|
+
if (value === undefined) return undefined;
|
|
33
|
+
const list = typeof value === "string" ? value.split(",") : value;
|
|
34
|
+
if (!Array.isArray(list)) throw new SearchError("scope must be one of wiki, memory or chats");
|
|
35
|
+
const found: SearchScope[] = [];
|
|
36
|
+
for (const item of list) {
|
|
37
|
+
const name = String(item).trim();
|
|
38
|
+
if (name.length === 0) continue;
|
|
39
|
+
const scope = SEARCH_SCOPES.find((candidate) => candidate === name);
|
|
40
|
+
if (scope === undefined) throw new SearchError(`unknown scope "${name}"`);
|
|
41
|
+
if (!found.includes(scope)) found.push(scope);
|
|
42
|
+
}
|
|
43
|
+
return found.length === 0 ? undefined : found;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function limitOf(value: unknown): number | undefined {
|
|
47
|
+
if (value === undefined || value === "") return undefined;
|
|
48
|
+
const number = typeof value === "number" ? value : Number(value);
|
|
49
|
+
if (!Number.isInteger(number)) throw new SearchError("limit must be a whole number");
|
|
50
|
+
return requestedLimit(number);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function jsonInput(input: string | undefined): Record<string, unknown> | undefined {
|
|
54
|
+
const text = input?.trim() ?? "";
|
|
55
|
+
if (!text.startsWith("{")) return undefined;
|
|
56
|
+
let parsed: unknown;
|
|
57
|
+
try {
|
|
58
|
+
parsed = JSON.parse(text);
|
|
59
|
+
} catch (error) {
|
|
60
|
+
throw new SearchError(`the search arguments are not JSON: ${String(error)}`);
|
|
61
|
+
}
|
|
62
|
+
if (!isRecord(parsed)) throw new SearchError("the search arguments must be a JSON object");
|
|
63
|
+
return parsed;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface SearchInput {
|
|
67
|
+
readonly query: string;
|
|
68
|
+
readonly scopes?: readonly SearchScope[] | undefined;
|
|
69
|
+
readonly fields?: Readonly<Record<string, string | readonly string[]>> | undefined;
|
|
70
|
+
readonly limit?: number | undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function searchFromJson(parsed: Record<string, unknown>): SearchInput {
|
|
74
|
+
const query = textOf(parsed["query"] ?? parsed["text"], "query");
|
|
75
|
+
const scopes = scopesOf(parsed["scope"] ?? parsed["scopes"]);
|
|
76
|
+
const fields = parsed["fields"] === undefined ? undefined : fieldFiltersOf(parsed["fields"]);
|
|
77
|
+
const limit = limitOf(parsed["limit"]);
|
|
78
|
+
return { query, ...(scopes === undefined ? {} : { scopes }), ...(fields === undefined ? {} : { fields }), ...(limit === undefined ? {} : { limit }) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function searchFromArgv(argv: readonly string[]): SearchInput {
|
|
82
|
+
const words: string[] = [];
|
|
83
|
+
const scopes: string[] = [];
|
|
84
|
+
const fields: Record<string, string> = {};
|
|
85
|
+
let limit: string | undefined;
|
|
86
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
87
|
+
const arg = argv[index] ?? "";
|
|
88
|
+
if (arg === "--scope" || arg.startsWith("--scope=")) {
|
|
89
|
+
const value = arg === "--scope" ? argv[++index] ?? "" : arg.slice("--scope=".length);
|
|
90
|
+
scopes.push(value);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (arg === "--field" || arg.startsWith("--field=")) {
|
|
94
|
+
const value = arg === "--field" ? argv[++index] ?? "" : arg.slice("--field=".length);
|
|
95
|
+
const at = value.indexOf("=");
|
|
96
|
+
if (at <= 0) throw new SearchError("--field takes <name>=<value>");
|
|
97
|
+
fields[value.slice(0, at)] = value.slice(at + 1);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (arg === "--limit" || arg.startsWith("--limit=")) {
|
|
101
|
+
limit = arg === "--limit" ? argv[++index] ?? "" : arg.slice("--limit=".length);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (arg.startsWith("--")) throw new SearchError(`search does not take "${arg}"`);
|
|
105
|
+
words.push(arg);
|
|
106
|
+
}
|
|
107
|
+
if (words.length === 0) throw new SearchError("search needs a query");
|
|
108
|
+
return {
|
|
109
|
+
query: words.join(" "),
|
|
110
|
+
...(scopes.length === 0 ? {} : { scopes: scopesOf(scopes) }),
|
|
111
|
+
...(Object.keys(fields).length === 0 ? {} : { fields }),
|
|
112
|
+
...(limit === undefined ? {} : { limit: limitOf(limit) }),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function searchInput(ctx: CommandContext, argv: readonly string[]): SearchInput {
|
|
117
|
+
const parsed = jsonInput(ctx.input);
|
|
118
|
+
return parsed === undefined ? searchFromArgv(argv) : searchFromJson(parsed);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface ReadInput {
|
|
122
|
+
readonly id: string;
|
|
123
|
+
readonly from?: number | undefined;
|
|
124
|
+
readonly to?: number | undefined;
|
|
125
|
+
readonly json: boolean;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function lineNumber(value: unknown, name: string): number | undefined {
|
|
129
|
+
if (value === undefined || value === "") return undefined;
|
|
130
|
+
const number = typeof value === "number" ? value : Number(value);
|
|
131
|
+
if (!Number.isInteger(number) || number < 1) throw new SearchError(`${name} must be a whole line number above zero`);
|
|
132
|
+
return number;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function readInput(ctx: CommandContext, argv: readonly string[]): ReadInput {
|
|
136
|
+
const parsed = jsonInput(ctx.input);
|
|
137
|
+
if (parsed !== undefined) {
|
|
138
|
+
return {
|
|
139
|
+
id: textOf(parsed["id"], "id"),
|
|
140
|
+
...(parsed["from"] === undefined ? {} : { from: lineNumber(parsed["from"], "from") }),
|
|
141
|
+
...(parsed["to"] === undefined ? {} : { to: lineNumber(parsed["to"], "to") }),
|
|
142
|
+
json: true,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
const words: string[] = [];
|
|
146
|
+
let json = false;
|
|
147
|
+
for (const arg of argv) {
|
|
148
|
+
if (arg === "--json") json = true;
|
|
149
|
+
else words.push(arg);
|
|
150
|
+
}
|
|
151
|
+
const id = words[0];
|
|
152
|
+
if (id === undefined || id.length === 0) throw new SearchError("read needs a document id");
|
|
153
|
+
return {
|
|
154
|
+
id,
|
|
155
|
+
...(words[1] === undefined ? {} : { from: lineNumber(words[1], "from") }),
|
|
156
|
+
...(words[2] === undefined ? {} : { to: lineNumber(words[2], "to") }),
|
|
157
|
+
json,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** One backlink as a line a reader can follow. */
|
|
162
|
+
function backlinkLine(entry: Backlink): string {
|
|
163
|
+
const line = entry.line > 0 ? ` line ${entry.line}` : "";
|
|
164
|
+
const mark = entry.untrusted ? " (untrusted)" : "";
|
|
165
|
+
const excerpt = entry.excerpt.length > 0 ? ` — ${entry.excerpt}` : "";
|
|
166
|
+
return `- \`${entry.path}\`${line}${mark}${excerpt}`;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** One document as the command prints it, ending with its backlinks. */
|
|
170
|
+
export function readText(result: ReadResult): string {
|
|
171
|
+
const lines = [`# ${result.title}`, ""];
|
|
172
|
+
lines.push(`- id: \`${result.id}\``);
|
|
173
|
+
if (result.path !== undefined) lines.push(`- path: ${result.path}`);
|
|
174
|
+
lines.push(`- lines: ${result.lineStart}-${result.lineEnd} of ${result.totalLines}`);
|
|
175
|
+
if (result.text.length > 0) lines.push("", result.text);
|
|
176
|
+
if (result.backlinks.length > 0) {
|
|
177
|
+
lines.push("", "## Backlinks");
|
|
178
|
+
for (const entry of result.backlinks) lines.push(backlinkLine(entry));
|
|
179
|
+
}
|
|
180
|
+
return `${lines.join("\n")}\n`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The `memory search` verb. */
|
|
184
|
+
export async function runMemorySearch(ctx: CommandContext, argv: readonly string[]): Promise<unknown> {
|
|
185
|
+
const input = searchInput(ctx, argv);
|
|
186
|
+
const search = openMemorySearch(ctx.home, ctx.settings);
|
|
187
|
+
try {
|
|
188
|
+
await search.refresh(ctx.store);
|
|
189
|
+
return search.search({
|
|
190
|
+
text: input.query,
|
|
191
|
+
cwd: ctx.cwd,
|
|
192
|
+
...(input.scopes === undefined ? {} : { scopes: requestedScopes(input.scopes) }),
|
|
193
|
+
...(input.fields === undefined ? {} : { fields: input.fields }),
|
|
194
|
+
...(input.limit === undefined ? {} : { limit: input.limit }),
|
|
195
|
+
});
|
|
196
|
+
} finally {
|
|
197
|
+
search.close();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** The `memory read` verb: one document, or the line range asked for. */
|
|
202
|
+
export async function runMemoryRead(ctx: CommandContext, argv: readonly string[]): Promise<unknown> {
|
|
203
|
+
const input = readInput(ctx, argv);
|
|
204
|
+
const search = openMemorySearch(ctx.home, ctx.settings);
|
|
205
|
+
try {
|
|
206
|
+
await search.refresh(ctx.store);
|
|
207
|
+
const result = search.read({
|
|
208
|
+
id: input.id,
|
|
209
|
+
...(input.from === undefined ? {} : { from: input.from }),
|
|
210
|
+
...(input.to === undefined ? {} : { to: input.to }),
|
|
211
|
+
});
|
|
212
|
+
return input.json ? result : readText(result);
|
|
213
|
+
} finally {
|
|
214
|
+
search.close();
|
|
215
|
+
}
|
|
216
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of Markdown a search reads: frontmatter as fields for a filter, and
|
|
3
|
+
* the body as text for the index. The parser is deliberately small: the keys
|
|
4
|
+
* and values a note uses for its title, tags and dates. A structure it does not
|
|
5
|
+
* understand is left out of the fields rather than guessed at.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { DocumentFields } from "./types.ts";
|
|
9
|
+
|
|
10
|
+
/** A body with the fields its frontmatter stated. */
|
|
11
|
+
export interface SplitMarkdown {
|
|
12
|
+
readonly fields: DocumentFields;
|
|
13
|
+
readonly body: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const KEY = /^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/;
|
|
17
|
+
|
|
18
|
+
function unquote(value: string): string {
|
|
19
|
+
const trimmed = value.trim();
|
|
20
|
+
if (trimmed.length >= 2 && trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
|
|
21
|
+
return trimmed.slice(1, -1).replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
|
|
22
|
+
}
|
|
23
|
+
if (trimmed.length >= 2 && trimmed.startsWith("'") && trimmed.endsWith("'")) {
|
|
24
|
+
return trimmed.slice(1, -1).replace(/''/g, "'");
|
|
25
|
+
}
|
|
26
|
+
return trimmed;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function scalar(value: string): string {
|
|
30
|
+
const text = unquote(value);
|
|
31
|
+
// A comment after an unquoted scalar is not part of it. A `#` inside a note
|
|
32
|
+
// tag or a colour would be, so only a space before it starts a comment.
|
|
33
|
+
return text.replace(/\s+#.*$/u, "").trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function list(value: string): string[] {
|
|
37
|
+
const inner = value.trim().slice(1, -1);
|
|
38
|
+
return inner
|
|
39
|
+
.split(",")
|
|
40
|
+
.map((item) => scalar(item))
|
|
41
|
+
.filter((item) => item.length > 0);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Splits Markdown into its frontmatter fields and the body that follows. Text
|
|
46
|
+
* without a closed frontmatter block is all body.
|
|
47
|
+
*/
|
|
48
|
+
export function splitMarkdown(raw: string): SplitMarkdown {
|
|
49
|
+
const text = raw.startsWith("\uFEFF") ? raw.slice(1) : raw;
|
|
50
|
+
if (!text.startsWith("---\n") && !text.startsWith("---\r\n")) {
|
|
51
|
+
return { fields: {}, body: text };
|
|
52
|
+
}
|
|
53
|
+
const lines = text.split(/\r?\n/);
|
|
54
|
+
let end = -1;
|
|
55
|
+
for (let index = 1; index < lines.length; index += 1) {
|
|
56
|
+
if (lines[index]?.trim() === "---") {
|
|
57
|
+
end = index;
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (end < 0) return { fields: {}, body: text };
|
|
62
|
+
|
|
63
|
+
const found = new Map<string, string[]>();
|
|
64
|
+
let current: string | undefined;
|
|
65
|
+
for (const line of lines.slice(1, end)) {
|
|
66
|
+
const trimmed = line.trim();
|
|
67
|
+
if (trimmed.length === 0 || trimmed.startsWith("#")) continue;
|
|
68
|
+
const item = /^-\s*(.*)$/u.exec(trimmed);
|
|
69
|
+
if (item !== null && current !== undefined) {
|
|
70
|
+
const value = scalar(item[1] ?? "");
|
|
71
|
+
if (value.length > 0) found.get(current)?.push(value);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const match = KEY.exec(line);
|
|
75
|
+
if (match === null) {
|
|
76
|
+
current = undefined;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const key = match[1] ?? "";
|
|
80
|
+
const value = (match[2] ?? "").trim();
|
|
81
|
+
current = key;
|
|
82
|
+
const values = found.get(key) ?? [];
|
|
83
|
+
if (value.startsWith("[") && value.endsWith("]")) {
|
|
84
|
+
values.push(...list(value));
|
|
85
|
+
} else if (value.length > 0) {
|
|
86
|
+
const one = scalar(value);
|
|
87
|
+
if (one.length > 0) values.push(one);
|
|
88
|
+
}
|
|
89
|
+
found.set(key, values);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const fields: Record<string, readonly string[]> = {};
|
|
93
|
+
for (const [key, values] of found) {
|
|
94
|
+
// A key with no value (a block list that had no items) is not a filter.
|
|
95
|
+
if (values.length > 0) fields[key.toLowerCase()] = [...values];
|
|
96
|
+
}
|
|
97
|
+
return { fields, body: lines.slice(end + 1).join("\n") };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The title a reader sees: frontmatter `title`, a heading, or the file name. */
|
|
101
|
+
export function titleOf(fields: DocumentFields, body: string, fallback: string): string {
|
|
102
|
+
const stated = fields["title"]?.[0];
|
|
103
|
+
if (stated !== undefined && stated.length > 0) return stated;
|
|
104
|
+
for (const line of body.split(/\r?\n/u)) {
|
|
105
|
+
const heading = /^#{1,6}\s+(.+?)\s*#*\s*$/u.exec(line);
|
|
106
|
+
if (heading !== null && heading[1] !== undefined && heading[1].length > 0) return heading[1];
|
|
107
|
+
}
|
|
108
|
+
return fallback;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A file name without its Markdown extension. */
|
|
112
|
+
export function titleFromName(name: string): string {
|
|
113
|
+
return name.replace(/\.(?:md|markdown)$/iu, "");
|
|
114
|
+
}
|