@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yinghai Zhao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # @operad-io/memory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The memory plugin.** It owns the shared wiki and a bot's memory: a Markdown
4
+ directory with a git history, a SQLite FTS5 index of the wiki, the memory and a
5
+ bot's chats, the `memory` skill every bot mounts, and the commit that records
6
+ what a bot reply wrote. A new home turns it on; a home made before needs
7
+ `operad plugin enable memory`.
8
+
9
+ This package is part of [operad](https://github.com/operad-io/operad). Most people install only [`@operad-io/cli`](https://www.npmjs.com/package/@operad-io/cli).
10
+
11
+ ## Documentation
12
+
13
+ - User guide: [docs/user/memory.md](https://github.com/operad-io/operad/blob/main/docs/user/memory.md)
14
+ - Website: <https://operad.io>
15
+ - Developer reference: `REFERENCE.md` in this directory
16
+
17
+ MIT licensed.
@@ -0,0 +1,17 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://operad.io/schemas/memory.schema.json",
4
+ "title": "operad memory settings",
5
+ "description": "The `memory` section of config.json, owned by the memory plugin.",
6
+ "type": "object",
7
+ "properties": {
8
+ "wikiDir": {
9
+ "type": "string",
10
+ "title": "Wiki directory",
11
+ "minLength": 1,
12
+ "default": "wiki",
13
+ "description": "The shared knowledge base: a Markdown directory every bot reads, and the bots whose access profile allows it write. Created when missing and made a git repository when it is not one; a directory that is already a git repository is used as it is, never re-initialised or restructured. `~` is your home directory and a relative path is under the operad home. Default: `wiki` in the operad home, so ~/.operad/wiki for the usual home; a person may point it at a notes library such as an Obsidian vault."
14
+ }
15
+ },
16
+ "additionalProperties": false
17
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@operad-io/memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts"
7
+ },
8
+ "dependencies": {
9
+ "@operad-io/engine": "0.2.0"
10
+ },
11
+ "description": "operad: the memory plugin and the wiki",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/operad-io/operad.git",
15
+ "directory": "packages/memory"
16
+ },
17
+ "license": "MIT",
18
+ "files": [
19
+ "src",
20
+ "skills",
21
+ "memory.schema.json",
22
+ "README.md",
23
+ "LICENSE"
24
+ ]
25
+ }
@@ -0,0 +1,84 @@
1
+ ---
2
+ name: memory
3
+ description: What this bot remembers and where the shared wiki is. Read it before answering; write to it without asking. Use it for what you cannot look up: preferences, corrections and rules a person verified.
4
+ ---
5
+
6
+ # Memory
7
+
8
+ Your memory is the `memory/` directory in your working directory. The wiki is
9
+ the shared knowledge base every bot reads: `~/.operad/wiki` unless a person set
10
+ another directory. A person may point the wiki at their own notes library, and
11
+ its files are theirs.
12
+
13
+ ## Read it before you answer
14
+
15
+ - Read `memory/index.md` and `memory/instructions.md` before you answer a
16
+ question that may depend on what you already know.
17
+ - Search before you say you do not know. Use the `search` tool, which reaches
18
+ the wiki, your memory and your own chats. Try several phrasings: a keyword or
19
+ two, then a natural question; a Chinese phrase and a mixed Chinese/English
20
+ one. A search returns a document id and line range; read it with `read`.
21
+ Narrow the search with `scope` (`wiki`, `memory`, `chats`) or with frontmatter
22
+ `fields`, and read the directory note a hit brings with it.
23
+ - `instructions.md` holds the person's long-standing instructions to you. Follow
24
+ them; they are not notes to weigh.
25
+ - When a note no longer matches what you see now, trust what you see and correct
26
+ the note.
27
+
28
+ ## What belongs in memory
29
+
30
+ Only what you cannot look up: a person's preferences, a correction they made,
31
+ and a rule they verified. operad already keeps plans, tasks and the history of
32
+ what happened; the wiki keeps notes about the world. Point at those instead of
33
+ copying them: link the page, or name the task or flow.
34
+
35
+ Rules you must obey do not go in memory. They live in your instructions and your
36
+ access profile. When a rule should change, propose the change to a person; do
37
+ not write it into a note.
38
+
39
+ ## How it is laid out
40
+
41
+ - `memory/index.md`: the index, one line per entry, a link and a few words. Keep
42
+ it short (under about 8,000 characters); when a line grows, move the detail to
43
+ a topic note and leave the link.
44
+ - `memory/log/YYYY-MM-DD.md`: an append-only daily log of what happened. Never
45
+ rewrite an earlier entry; add a new one.
46
+ - `memory/topics/<name>.md`: topic notes, linked from the index. This is where
47
+ the detail lives.
48
+ - `memory/instructions.md`: a person's long-standing instructions to you, in
49
+ their words.
50
+
51
+ Write without asking. Keep edits small, supersede an old note instead of
52
+ deleting it, and say in the new note what it replaces.
53
+
54
+ ## Content you did not have before
55
+
56
+ When you write a note after reading a web page, mail, or an item a source
57
+ plugin fetched, mark it in the frontmatter:
58
+
59
+ ```md
60
+ ---
61
+ untrusted: true
62
+ ---
63
+ ```
64
+
65
+ Such a note is never put in `memory/index.md`, and an index line pointing at it
66
+ is removed. Keep it out of the index yourself, and do not promote it later. If
67
+ you are not sure whether what you read was untrusted, say so in the note instead
68
+ of guessing.
69
+
70
+ The wiki is where durable notes about the world go. Your memory points at it and
71
+ keeps what is about this person and this bot.
72
+
73
+ ## Searching
74
+
75
+ The index is built from the wiki, your `memory/` directory and the chats of this
76
+ bot. It is refreshed as those change; a note a person edits in their editor is
77
+ found on your next search. A directory may hold an `_about.md` that says what
78
+ the directory is for; it comes back with hits found inside that directory.
79
+
80
+ Search is a first step, not a verdict. If the first words find nothing, try a
81
+ synonym, a shorter phrase, the name of the person or project, or a sentence as
82
+ someone would say it. Then read the document, because a snippet is only a few
83
+ lines. A read ends with a `Backlinks` section when other notes link to it; follow
84
+ those notes when the one you read is thin or one-sided.
package/src/commit.ts ADDED
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Recording what a bot wrote: one commit per reply run in each repository the
3
+ * run changed, in the bot's memory and in the shared wiki. Content a note marks
4
+ * as coming from untrusted material is kept out of `memory/index.md`; the note
5
+ * itself stays where it was written.
6
+ */
7
+
8
+ import { messageOf } from "@operad-io/engine";
9
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { withLockFile } from "@operad-io/engine/platform";
12
+ import { isRecord, type JsonValue, type PluginStepResult, type StepContext } from "@operad-io/engine";
13
+ import {
14
+ MEMORY_COMMIT_STEP,
15
+ ensureMemoryLayout,
16
+ ensureRepository,
17
+ ensureWiki,
18
+ memoryGit,
19
+ pathIn,
20
+ type Repository,
21
+ } from "./memory.ts";
22
+ import {
23
+ TIDY_APPEND_ONLY_NOTE,
24
+ TIDY_COMMIT_FACT,
25
+ TIDY_ORIGIN,
26
+ applyAppendOnly,
27
+ lastTidyCommit,
28
+ rewriteDrop,
29
+ } from "./tidy.ts";
30
+ import { parseNoteLinks, resolveNoteLink } from "./links.ts";
31
+
32
+ /** The lock one home's memory commits take turns under. */
33
+ export const COMMIT_LOCK = "memory-commit.lock";
34
+
35
+ /** The identity a commit is made with, so a home without one still records its writes. */
36
+ const COMMIT_IDENTITY: readonly string[] = [
37
+ "-c",
38
+ "user.name=operad memory",
39
+ "-c",
40
+ "user.email=memory@operad.local",
41
+ "-c",
42
+ "commit.gpgsign=false",
43
+ ];
44
+
45
+ /** One commit the step made. */
46
+ export interface CommitInfo {
47
+ /** The repository root. */
48
+ readonly root: string;
49
+ /** The paths, relative to the root, that the commit holds. */
50
+ readonly paths: readonly string[];
51
+ /** The commit's subject. */
52
+ readonly message: string;
53
+ }
54
+
55
+ /** A note whose frontmatter says it came from untrusted content. */
56
+ export function untrustedNotes(memoryDir: string): string[] {
57
+ const found: string[] = [];
58
+ const visit = (directory: string, prefix: string): void => {
59
+ if (!existsSync(directory)) return;
60
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
61
+ if (entry.name === ".git") continue;
62
+ const path = join(directory, entry.name);
63
+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
64
+ if (entry.isDirectory()) {
65
+ visit(path, rel);
66
+ continue;
67
+ }
68
+ if (!entry.name.endsWith(".md") || rel === "index.md") continue;
69
+ if (isUntrusted(path)) found.push(rel);
70
+ }
71
+ };
72
+ visit(memoryDir, "");
73
+ return found.sort();
74
+ }
75
+
76
+ /** Reads only the YAML frontmatter of a note; `untrusted: true` marks it. */
77
+ function isUntrusted(path: string): boolean {
78
+ let text: string;
79
+ try {
80
+ text = readFileSync(path, "utf8");
81
+ } catch {
82
+ return false;
83
+ }
84
+ const lines = text.split("\n");
85
+ if ((lines[0] ?? "").trim() !== "---") return false;
86
+ for (let index = 1; index < lines.length; index += 1) {
87
+ const line = lines[index] ?? "";
88
+ if (line.trim() === "---") return false;
89
+ if (/^untrusted:\s*true\s*$/i.test(line.trim())) return true;
90
+ }
91
+ return false;
92
+ }
93
+
94
+ /**
95
+ * The index without the lines that link to an untrusted note. A whole line goes,
96
+ * because one line is one entry; every other line stays as it was. The link
97
+ * forms are the ones the search index reads (`parseNoteLinks`), and a target is
98
+ * resolved the same way (`resolveNoteLink`): the index sits at the scope root,
99
+ * so a bare name may name a note in any folder.
100
+ */
101
+ export function withoutUntrustedLines(index: string, untrusted: readonly string[]): string {
102
+ if (untrusted.length === 0) return index;
103
+ const kept: string[] = [];
104
+ for (const line of index.split("\n")) {
105
+ const marked = parseNoteLinks(line).some(
106
+ (link) => resolveNoteLink("index.md", link, untrusted) !== undefined,
107
+ );
108
+ if (!marked) kept.push(line);
109
+ }
110
+ return kept.join("\n");
111
+ }
112
+
113
+ /** Keeps untrusted notes out of the bot's index; returns the notes it removed a line for. */
114
+ export function stripUntrustedFromIndex(memoryDir: string): { readonly removed: readonly string[]; readonly changed: boolean } {
115
+ const index = join(memoryDir, "index.md");
116
+ if (!existsSync(index)) return { removed: [], changed: false };
117
+ const notes = untrustedNotes(memoryDir);
118
+ const text = readFileSync(index, "utf8");
119
+ const next = withoutUntrustedLines(text, notes);
120
+ if (next === text) return { removed: [], changed: false };
121
+ writeFileSync(index, next);
122
+ return { removed: notes, changed: true };
123
+ }
124
+
125
+ /**
126
+ * Commits the changes under one directory of a repository, and nothing else.
127
+ * An unchanged directory makes no commit, so a run that wrote nothing records
128
+ * nothing. Returns undefined for that case.
129
+ */
130
+ export function commitChanges(
131
+ repository: Repository,
132
+ directory: string,
133
+ message: string,
134
+ options: { readonly allowEmpty?: boolean | undefined } = {},
135
+ ): CommitInfo | undefined {
136
+ const paths = pathIn(repository.root, directory);
137
+ const status = memoryGit(repository.root, ["status", "--porcelain", "--", paths]);
138
+ if (!status.ok) {
139
+ throw new Error(`git status in ${repository.root} failed: ${status.err || "git wrote nothing"}`);
140
+ }
141
+ if (status.out.length === 0 && options.allowEmpty !== true) return undefined;
142
+ const added = memoryGit(repository.root, ["add", "-A", "--", paths]);
143
+ if (!added.ok) {
144
+ throw new Error(`git add in ${repository.root} failed: ${added.err || "git wrote nothing"}`);
145
+ }
146
+ const committed = memoryGit(repository.root, [
147
+ ...COMMIT_IDENTITY,
148
+ "commit",
149
+ ...(options.allowEmpty === true ? ["--allow-empty"] : []),
150
+ "--no-verify",
151
+ "-m",
152
+ message,
153
+ "--",
154
+ paths,
155
+ ]);
156
+ if (!committed.ok) {
157
+ throw new Error(`git commit in ${repository.root} failed: ${committed.err || "git wrote nothing"}`);
158
+ }
159
+ return { root: repository.root, paths: [paths], message };
160
+ }
161
+
162
+ /** What one bot run changed, as the step reports it. */
163
+ export interface MemoryCommitData {
164
+ readonly bot: string;
165
+ readonly chat: string;
166
+ readonly memory: CommitInfo | null;
167
+ readonly wiki: CommitInfo | null;
168
+ readonly unindexed: readonly string[];
169
+ }
170
+
171
+ /** The bot and chat a commit step was called for. */
172
+ interface BotChat {
173
+ readonly bot: string;
174
+ readonly chat: string;
175
+ readonly cwd: string;
176
+ /** A tidy run's chat; its commit is what the next check measures from. */
177
+ readonly tidy: boolean;
178
+ }
179
+
180
+ function scheduledOrigin(stored: Readonly<Record<string, unknown>>): string | undefined {
181
+ const scheduled = stored["scheduled"];
182
+ return isRecord(scheduled) && typeof scheduled["entry"] === "string"
183
+ ? scheduled["entry"]
184
+ : undefined;
185
+ }
186
+
187
+ function botChatOf(stored: Readonly<Record<string, unknown>> | undefined, chat: string): BotChat | undefined {
188
+ if (stored === undefined) return undefined;
189
+ const parent = typeof stored["parent"] === "string" ? stored["parent"] : "";
190
+ const cwd = typeof stored["cwd"] === "string" ? stored["cwd"] : "";
191
+ if (!parent.startsWith("bot:") || cwd.length === 0) return undefined;
192
+ return {
193
+ bot: parent.slice("bot:".length),
194
+ chat,
195
+ cwd,
196
+ tidy: scheduledOrigin(stored) === TIDY_ORIGIN,
197
+ };
198
+ }
199
+
200
+ /**
201
+ * The message a commit names the bot and the chat with. The two repositories
202
+ * get a word each, so a person reading `git log` sees which part changed.
203
+ */
204
+ export function commitMessage(part: "memory" | "wiki" | "tidy", bot: string, chat: string): string {
205
+ return `${part}: bot ${bot}, chat ${chat}`;
206
+ }
207
+
208
+ /** Commits the bot's memory and the shared wiki; throws with the reason when git refuses. */
209
+ export async function commitBotRun(
210
+ home: string,
211
+ bot: BotChat,
212
+ settings: Readonly<Record<string, JsonValue>>,
213
+ ): Promise<MemoryCommitData> {
214
+ return withLockFile(
215
+ join(home, COMMIT_LOCK),
216
+ () => {
217
+ const memoryDir = join(bot.cwd, "memory");
218
+ ensureMemoryLayout(memoryDir);
219
+ const index = stripUntrustedFromIndex(memoryDir);
220
+ const repository = ensureRepository(memoryDir);
221
+ let message = commitMessage(bot.tidy ? "tidy" : "memory", bot.bot, bot.chat);
222
+ if (bot.tidy) {
223
+ const baseline = lastTidyCommit(repository, memoryDir, bot.bot);
224
+ if (baseline !== undefined && rewriteDrop(repository, memoryDir, baseline).voided) {
225
+ applyAppendOnly(repository, memoryDir, baseline);
226
+ message = `${message}\n\n${TIDY_APPEND_ONLY_NOTE}`;
227
+ }
228
+ }
229
+ const memory = commitChanges(repository, memoryDir, message, { allowEmpty: bot.tidy });
230
+ const wiki = ensureWiki(home, settings);
231
+ const wikiIndex = stripUntrustedFromIndex(wiki.directory);
232
+ const wikiCommit = commitChanges(wiki, wiki.directory, commitMessage("wiki", bot.bot, bot.chat));
233
+ return {
234
+ bot: bot.bot,
235
+ chat: bot.chat,
236
+ memory: memory ?? null,
237
+ wiki: wikiCommit ?? null,
238
+ unindexed: [...new Set([...index.removed, ...wikiIndex.removed])],
239
+ };
240
+ },
241
+ { label: "memory" },
242
+ );
243
+ }
244
+
245
+ /**
246
+ * Step `memory/commit`: called after a bot chat's reply. It writes nothing of
247
+ * the bot's own; it records what the run wrote, in one commit per repository.
248
+ */
249
+ export async function runMemoryCommit(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
250
+ const fromParams = isRecord(params) && typeof params.chat === "string" ? params.chat : undefined;
251
+ const chat = fromParams ?? (ctx.object?.type === "chat" ? ctx.object.id : undefined);
252
+ if (chat === undefined) {
253
+ return { result: "failed", data: { message: `${MEMORY_COMMIT_STEP} needs the chat it follows` } };
254
+ }
255
+ const stored = await ctx.store.get("chat", chat);
256
+ const target = botChatOf(stored?.data, chat);
257
+ if (target === undefined) {
258
+ return { result: "done", data: { skipped: "not a chat of a bot" } };
259
+ }
260
+ let outcome: PluginStepResult;
261
+ try {
262
+ const data = await commitBotRun(ctx.home, target, ctx.settings);
263
+ outcome = { result: "done", data: data as unknown as Record<string, JsonValue> };
264
+ } catch (error) {
265
+ outcome = {
266
+ result: "failed",
267
+ data: { message: messageOf(error) },
268
+ };
269
+ }
270
+ if (target.tidy) {
271
+ await ctx.facts.append({
272
+ type: TIDY_COMMIT_FACT,
273
+ object: { type: "chat", id: chat },
274
+ data: { chat, ok: outcome.result === "done" },
275
+ });
276
+ }
277
+ return outcome;
278
+ }
279
+
package/src/index.ts ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The memory plugin: the shared wiki and the bot's memory. It owns the wiki
3
+ * directory setting, the `memory` skill every bot mounts, and the commit that
4
+ * records what a reply wrote. The wiki is also read-only objects for the apps:
5
+ * its folders and notes, projected from the Markdown directory.
6
+ */
7
+
8
+ import pkg from "../package.json" with { type: "json" };
9
+ import { definePlugin, type JsonValue, type ObjectStore } from "@operad-io/engine";
10
+ import { watchDirectory } from "@operad-io/engine/platform";
11
+ import { MEMORY_SETTINGS, ensureWiki, wikiDirectory } from "./memory.ts";
12
+ import { runMemoryCommit } from "./commit.ts";
13
+ import { openMemorySearch } from "./search/service.ts";
14
+ import { runMemoryRead, runMemorySearch } from "./search/command.ts";
15
+ import { botMemoryDirectories } from "./search/sources.ts";
16
+ import {
17
+ WIKI_FOLDER_TYPE,
18
+ WIKI_NOTE_TYPE,
19
+ resolveWikiFolderId,
20
+ resolveWikiNoteId,
21
+ syncWikiObjects,
22
+ wikiFolderViews,
23
+ wikiNoteViews,
24
+ } from "./wiki.ts";
25
+
26
+ const WIKI_FILTERS = [
27
+ { name: "live", states: ["open"], default: true },
28
+ { name: "removed", states: ["removed"] },
29
+ ] as const;
30
+
31
+ /** The one scan both wiki types share, so a read does not rebuild it twice. */
32
+ function prepareWiki(
33
+ store: ObjectStore,
34
+ home: string,
35
+ settings: Readonly<Record<string, JsonValue>>,
36
+ ): Promise<void> {
37
+ return syncWikiObjects(store, home, settings);
38
+ }
39
+
40
+ /**
41
+ * A wiki path is claimed only when the wiki holds it, so a bare id that names
42
+ * another plugin's object (a task such as `T-0597-...`) is not made ambiguous
43
+ * by a folder or note that does not exist.
44
+ */
45
+ async function claimIfStored(
46
+ store: ObjectStore,
47
+ type: string,
48
+ path: string | undefined,
49
+ ): Promise<string | undefined> {
50
+ if (path === undefined) return undefined;
51
+ return (await store.get(type, path)) === undefined ? undefined : path;
52
+ }
53
+
54
+ /** Builds the memory plugin. */
55
+ export function createMemoryPlugin() {
56
+ return definePlugin({
57
+ name: "memory",
58
+ kind: "domain",
59
+ // The version comes from package.json so the two cannot drift apart.
60
+ version: pkg.version,
61
+ settings: MEMORY_SETTINGS,
62
+ objects: [
63
+ {
64
+ name: WIKI_FOLDER_TYPE,
65
+ filters: WIKI_FILTERS,
66
+ resolve: (ctx, type, id) => claimIfStored(ctx.store, type, resolveWikiFolderId(id)),
67
+ // This scan writes the notes too, so only one type declares it.
68
+ prepare: ({ store, home, settings }) => prepareWiki(store, home, settings),
69
+ },
70
+ {
71
+ name: WIKI_NOTE_TYPE,
72
+ filters: WIKI_FILTERS,
73
+ resolve: (ctx, type, id) => claimIfStored(ctx.store, type, resolveWikiNoteId(id)),
74
+ },
75
+ ],
76
+ steps: [{ name: "commit", results: ["done", "failed"], run: runMemoryCommit }],
77
+ commands: [
78
+ { name: "search", args: "[--scope <scope>] [--field <name>=<value>] [--limit <n>] <query>", run: runMemorySearch },
79
+ { name: "read", args: "<id> [from] [to] [--json]", run: runMemoryRead },
80
+ ],
81
+ // The wiki is there before the first bot needs it; a directory that is
82
+ // already a git repository is used as it is. The index is brought up to
83
+ // date once, then a directory watch and the store's change listener make
84
+ // changes visible to a long-running server. A search refreshes too, so a
85
+ // change this process did not see is never missed.
86
+ start: async (ctx) => {
87
+ ensureWiki(ctx.home, ctx.settings);
88
+ const search = openMemorySearch(ctx.home, ctx.settings);
89
+ let stopped = false;
90
+ let pending: Promise<void> | undefined;
91
+ const refresh = (): void => {
92
+ if (stopped || pending !== undefined) return;
93
+ pending = syncWikiObjects(ctx.store, ctx.home, ctx.settings, search)
94
+ .then(() => undefined)
95
+ .catch(() => undefined)
96
+ .finally(() => {
97
+ pending = undefined;
98
+ });
99
+ };
100
+ void refresh();
101
+ const stops: (() => void)[] = [];
102
+ const watch = (directory: string): void => {
103
+ stops.push(watchDirectory(directory, () => refresh()));
104
+ };
105
+ watch(wikiDirectory(ctx.home, ctx.settings));
106
+ for (const memory of botMemoryDirectories(ctx.home)) watch(memory);
107
+ const unsubscribe = ctx.store.subscribe(() => refresh());
108
+ return {
109
+ stop: () => {
110
+ stopped = true;
111
+ for (const stop of stops) stop();
112
+ unsubscribe();
113
+ search.close();
114
+ },
115
+ };
116
+ },
117
+ views: {
118
+ [WIKI_FOLDER_TYPE]: wikiFolderViews,
119
+ [WIKI_NOTE_TYPE]: wikiNoteViews,
120
+ },
121
+ });
122
+ }
123
+
124
+ export default createMemoryPlugin();
125
+
126
+ export * from "./memory.ts";
127
+ export * from "./commit.ts";
128
+ export * from "./tidy.ts";
129
+ export * from "./search/types.ts";
130
+ export * from "./search/backend.ts";
131
+ export * from "./search/service.ts";
132
+ export * from "./search/frontmatter.ts";
133
+ export * from "./search/chunks.ts";
134
+ export * from "./links.ts";
135
+ export * from "./link-report.ts";
136
+ export * from "./search/sources.ts";
137
+ export * from "./search/command.ts";
138
+ export * from "./wiki.ts";