@operad-io/memory 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +16 -2
- package/memory.schema.json +17 -0
- package/package.json +23 -4
- package/skills/memory/SKILL.md +90 -0
- package/src/commit.ts +280 -0
- package/src/index.ts +138 -0
- package/src/link-report.ts +224 -0
- package/src/links.ts +378 -0
- package/src/memory.ts +230 -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
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
|
-
#
|
|
1
|
+
# @operad-io/memory
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": "./src/index.ts"
|
|
7
|
+
},
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@operad-io/engine": "0.3.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,90 @@
|
|
|
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
|
+
Work that spans several runs (a follow-up, a scheduled prompt, a long
|
|
52
|
+
task) keeps one progress file under your `memory/`, such as
|
|
53
|
+
`memory/topics/progress-<name>.md`, with one line in the index. Update that file
|
|
54
|
+
at the end of each run (what is done, what is next) and read it at the start of
|
|
55
|
+
the next, instead of starting again.
|
|
56
|
+
|
|
57
|
+
Write without asking. Keep edits small, supersede an old note instead of
|
|
58
|
+
deleting it, and say in the new note what it replaces.
|
|
59
|
+
|
|
60
|
+
## Content you did not have before
|
|
61
|
+
|
|
62
|
+
When you write a note after reading a web page, mail, or an item a source
|
|
63
|
+
plugin fetched, mark it in the frontmatter:
|
|
64
|
+
|
|
65
|
+
```md
|
|
66
|
+
---
|
|
67
|
+
untrusted: true
|
|
68
|
+
---
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Such a note is never put in `memory/index.md`, and an index line pointing at it
|
|
72
|
+
is removed. Keep it out of the index yourself, and do not promote it later. If
|
|
73
|
+
you are not sure whether what you read was untrusted, say so in the note instead
|
|
74
|
+
of guessing.
|
|
75
|
+
|
|
76
|
+
The wiki is where durable notes about the world go. Your memory points at it and
|
|
77
|
+
keeps what is about this person and this bot.
|
|
78
|
+
|
|
79
|
+
## Searching
|
|
80
|
+
|
|
81
|
+
The index is built from the wiki, your `memory/` directory and the chats of this
|
|
82
|
+
bot. It is refreshed as those change; a note a person edits in their editor is
|
|
83
|
+
found on your next search. A directory may hold an `_about.md` that says what
|
|
84
|
+
the directory is for; it comes back with hits found inside that directory.
|
|
85
|
+
|
|
86
|
+
Search is a first step, not a verdict. If the first words find nothing, try a
|
|
87
|
+
synonym, a shorter phrase, the name of the person or project, or a sentence as
|
|
88
|
+
someone would say it. Then read the document, because a snippet is only a few
|
|
89
|
+
lines. A read ends with a `Backlinks` section when other notes link to it; follow
|
|
90
|
+
those notes when the one you read is thin or one-sided.
|
package/src/commit.ts
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
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
|
+
if (!repository.tracked) return undefined;
|
|
137
|
+
const paths = pathIn(repository.root, directory);
|
|
138
|
+
const status = memoryGit(repository.root, ["status", "--porcelain", "--", paths]);
|
|
139
|
+
if (!status.ok) {
|
|
140
|
+
throw new Error(`git status in ${repository.root} failed: ${status.err || "git wrote nothing"}`);
|
|
141
|
+
}
|
|
142
|
+
if (status.out.length === 0 && options.allowEmpty !== true) return undefined;
|
|
143
|
+
const added = memoryGit(repository.root, ["add", "-A", "--", paths]);
|
|
144
|
+
if (!added.ok) {
|
|
145
|
+
throw new Error(`git add in ${repository.root} failed: ${added.err || "git wrote nothing"}`);
|
|
146
|
+
}
|
|
147
|
+
const committed = memoryGit(repository.root, [
|
|
148
|
+
...COMMIT_IDENTITY,
|
|
149
|
+
"commit",
|
|
150
|
+
...(options.allowEmpty === true ? ["--allow-empty"] : []),
|
|
151
|
+
"--no-verify",
|
|
152
|
+
"-m",
|
|
153
|
+
message,
|
|
154
|
+
"--",
|
|
155
|
+
paths,
|
|
156
|
+
]);
|
|
157
|
+
if (!committed.ok) {
|
|
158
|
+
throw new Error(`git commit in ${repository.root} failed: ${committed.err || "git wrote nothing"}`);
|
|
159
|
+
}
|
|
160
|
+
return { root: repository.root, paths: [paths], message };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** What one bot run changed, as the step reports it. */
|
|
164
|
+
export interface MemoryCommitData {
|
|
165
|
+
readonly bot: string;
|
|
166
|
+
readonly chat: string;
|
|
167
|
+
readonly memory: CommitInfo | null;
|
|
168
|
+
readonly wiki: CommitInfo | null;
|
|
169
|
+
readonly unindexed: readonly string[];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The bot and chat a commit step was called for. */
|
|
173
|
+
interface BotChat {
|
|
174
|
+
readonly bot: string;
|
|
175
|
+
readonly chat: string;
|
|
176
|
+
readonly cwd: string;
|
|
177
|
+
/** A tidy run's chat; its commit is what the next check measures from. */
|
|
178
|
+
readonly tidy: boolean;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function scheduledOrigin(stored: Readonly<Record<string, unknown>>): string | undefined {
|
|
182
|
+
const scheduled = stored["scheduled"];
|
|
183
|
+
return isRecord(scheduled) && typeof scheduled["entry"] === "string"
|
|
184
|
+
? scheduled["entry"]
|
|
185
|
+
: undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function botChatOf(stored: Readonly<Record<string, unknown>> | undefined, chat: string): BotChat | undefined {
|
|
189
|
+
if (stored === undefined) return undefined;
|
|
190
|
+
const parent = typeof stored["parent"] === "string" ? stored["parent"] : "";
|
|
191
|
+
const cwd = typeof stored["cwd"] === "string" ? stored["cwd"] : "";
|
|
192
|
+
if (!parent.startsWith("bot:") || cwd.length === 0) return undefined;
|
|
193
|
+
return {
|
|
194
|
+
bot: parent.slice("bot:".length),
|
|
195
|
+
chat,
|
|
196
|
+
cwd,
|
|
197
|
+
tidy: scheduledOrigin(stored) === TIDY_ORIGIN,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The message a commit names the bot and the chat with. The two repositories
|
|
203
|
+
* get a word each, so a person reading `git log` sees which part changed.
|
|
204
|
+
*/
|
|
205
|
+
export function commitMessage(part: "memory" | "wiki" | "tidy", bot: string, chat: string): string {
|
|
206
|
+
return `${part}: bot ${bot}, chat ${chat}`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Commits the bot's memory and the shared wiki; throws with the reason when git refuses. */
|
|
210
|
+
export async function commitBotRun(
|
|
211
|
+
home: string,
|
|
212
|
+
bot: BotChat,
|
|
213
|
+
settings: Readonly<Record<string, JsonValue>>,
|
|
214
|
+
): Promise<MemoryCommitData> {
|
|
215
|
+
return withLockFile(
|
|
216
|
+
join(home, COMMIT_LOCK),
|
|
217
|
+
() => {
|
|
218
|
+
const memoryDir = join(bot.cwd, "memory");
|
|
219
|
+
ensureMemoryLayout(memoryDir);
|
|
220
|
+
const index = stripUntrustedFromIndex(memoryDir);
|
|
221
|
+
const repository = ensureRepository(memoryDir);
|
|
222
|
+
let message = commitMessage(bot.tidy ? "tidy" : "memory", bot.bot, bot.chat);
|
|
223
|
+
if (bot.tidy) {
|
|
224
|
+
const baseline = lastTidyCommit(repository, memoryDir, bot.bot);
|
|
225
|
+
if (baseline !== undefined && rewriteDrop(repository, memoryDir, baseline).voided) {
|
|
226
|
+
applyAppendOnly(repository, memoryDir, baseline);
|
|
227
|
+
message = `${message}\n\n${TIDY_APPEND_ONLY_NOTE}`;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const memory = commitChanges(repository, memoryDir, message, { allowEmpty: bot.tidy });
|
|
231
|
+
const wiki = ensureWiki(home, settings);
|
|
232
|
+
const wikiIndex = stripUntrustedFromIndex(wiki.directory);
|
|
233
|
+
const wikiCommit = commitChanges(wiki, wiki.directory, commitMessage("wiki", bot.bot, bot.chat));
|
|
234
|
+
return {
|
|
235
|
+
bot: bot.bot,
|
|
236
|
+
chat: bot.chat,
|
|
237
|
+
memory: memory ?? null,
|
|
238
|
+
wiki: wikiCommit ?? null,
|
|
239
|
+
unindexed: [...new Set([...index.removed, ...wikiIndex.removed])],
|
|
240
|
+
};
|
|
241
|
+
},
|
|
242
|
+
{ label: "memory" },
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Step `memory/commit`: called after a bot chat's reply. It writes nothing of
|
|
248
|
+
* the bot's own; it records what the run wrote, in one commit per repository.
|
|
249
|
+
*/
|
|
250
|
+
export async function runMemoryCommit(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
|
|
251
|
+
const fromParams = isRecord(params) && typeof params.chat === "string" ? params.chat : undefined;
|
|
252
|
+
const chat = fromParams ?? (ctx.object?.type === "chat" ? ctx.object.id : undefined);
|
|
253
|
+
if (chat === undefined) {
|
|
254
|
+
return { result: "failed", data: { message: `${MEMORY_COMMIT_STEP} needs the chat it follows` } };
|
|
255
|
+
}
|
|
256
|
+
const stored = await ctx.store.get("chat", chat);
|
|
257
|
+
const target = botChatOf(stored?.data, chat);
|
|
258
|
+
if (target === undefined) {
|
|
259
|
+
return { result: "done", data: { skipped: "not a chat of a bot" } };
|
|
260
|
+
}
|
|
261
|
+
let outcome: PluginStepResult;
|
|
262
|
+
try {
|
|
263
|
+
const data = await commitBotRun(ctx.home, target, ctx.settings);
|
|
264
|
+
outcome = { result: "done", data: data as unknown as Record<string, JsonValue> };
|
|
265
|
+
} catch (error) {
|
|
266
|
+
outcome = {
|
|
267
|
+
result: "failed",
|
|
268
|
+
data: { message: messageOf(error) },
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
if (target.tidy) {
|
|
272
|
+
await ctx.facts.append({
|
|
273
|
+
type: TIDY_COMMIT_FACT,
|
|
274
|
+
object: { type: "chat", id: chat },
|
|
275
|
+
data: { chat, ok: outcome.result === "done" },
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
return outcome;
|
|
279
|
+
}
|
|
280
|
+
|
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";
|