@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/src/tidy.ts ADDED
@@ -0,0 +1,342 @@
1
+ /**
2
+ * The memory tidy's bookkeeping: what changed since the last tidy commit, how
3
+ * far the index is over its limit, and the guard that voids a rewrite which
4
+ * drops too many existing index entries and keeps only additions instead.
5
+ */
6
+
7
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
8
+ import { dirname, join, relative, sep } from "node:path";
9
+ import {
10
+ MEMORY_INDEX_MAX,
11
+ ensureRepository,
12
+ memoryGit,
13
+ pathIn,
14
+ type Repository,
15
+ } from "./memory.ts";
16
+
17
+ /** The origin a chat's data records for a tidy run. */
18
+ export const TIDY_ORIGIN = "memory-tidy";
19
+
20
+ /** The fact a tidy chat records once its memory commit was tried. */
21
+ export const TIDY_COMMIT_FACT = "memory.tidy";
22
+
23
+ /** The subject every tidy commit begins with. */
24
+ export const TIDY_SUBJECT = "tidy:";
25
+
26
+ /** The body a voided rewrite's commit carries. */
27
+ export const TIDY_APPEND_ONLY_NOTE =
28
+ "append only: the rewrite dropped too many existing entries, so only additions were kept";
29
+
30
+ /** How much of the old index a rewrite may drop before it is void. */
31
+ export const TIDY_MAX_DROP = 0.25;
32
+
33
+ /** What the last tidy left and what has happened since. */
34
+ export interface MemoryTidyState {
35
+ readonly repository: Repository;
36
+ /** The memory directory the state is about. */
37
+ readonly directory: string;
38
+ /** The last tidy commit, or undefined before the first one. */
39
+ readonly baseline: string | undefined;
40
+ /** When that commit was made, in milliseconds since the epoch. */
41
+ readonly since: number | undefined;
42
+ /** Notes added or changed since the baseline, relative to the memory directory. */
43
+ readonly notes: readonly string[];
44
+ /** The index's size in bytes, and whether it is over the limit. */
45
+ readonly indexBytes: number;
46
+ readonly indexOver: boolean;
47
+ }
48
+
49
+ function scoped(repository: Repository, directory: string): string {
50
+ return pathIn(repository.root, directory);
51
+ }
52
+
53
+ /**
54
+ * The latest tidy commit. With a bot name the subject names it, so an empty
55
+ * tidy commit counts too; without one the commit must touch the directory.
56
+ */
57
+ export function lastTidyCommit(
58
+ repository: Repository,
59
+ directory: string,
60
+ bot?: string,
61
+ ): string | undefined {
62
+ const found = memoryGit(repository.root, [
63
+ "log",
64
+ "-1",
65
+ "--format=%H",
66
+ `--grep=^${TIDY_SUBJECT}${bot === undefined ? "" : ` bot ${bot},`}`,
67
+ ...(bot === undefined ? ["--", scoped(repository, directory)] : []),
68
+ ]);
69
+ return found.ok && found.out.length > 0 ? found.out : undefined;
70
+ }
71
+
72
+ function commitTime(repository: Repository, commit: string): number | undefined {
73
+ const found = memoryGit(repository.root, ["log", "-1", "--format=%ct", commit]);
74
+ if (!found.ok) return undefined;
75
+ const seconds = Number(found.out);
76
+ return Number.isFinite(seconds) ? seconds * 1_000 : undefined;
77
+ }
78
+
79
+ /** A path relative to the memory directory, with `/` separators. */
80
+ function notePath(repository: Repository, directory: string, path: string): string | undefined {
81
+ const absolute = path.startsWith("/") ? path : join(repository.root, path);
82
+ const rel = relative(directory, absolute);
83
+ if (rel === "" || rel.startsWith("..")) return undefined;
84
+ return rel.split(sep).join("/");
85
+ }
86
+
87
+ function isNote(path: string): boolean {
88
+ return path.endsWith(".md") && path !== "index.md" && path !== "instructions.md";
89
+ }
90
+
91
+ /** Every Markdown note in a directory, relative to it. */
92
+ function notesOnDisk(directory: string): string[] {
93
+ const found: string[] = [];
94
+ const visit = (current: string, prefix: string): void => {
95
+ if (!existsSync(current)) return;
96
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
97
+ if (entry.name === ".git") continue;
98
+ const path = join(current, entry.name);
99
+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
100
+ if (entry.isDirectory()) {
101
+ visit(path, rel);
102
+ continue;
103
+ }
104
+ if (isNote(rel)) found.push(rel);
105
+ }
106
+ };
107
+ visit(directory, "");
108
+ return found;
109
+ }
110
+
111
+ /** The paths git reports as changed since a commit, including the working tree. */
112
+ function changedSince(repository: Repository, directory: string, baseline: string): string[] {
113
+ const found: string[] = [];
114
+ const committed = memoryGit(repository.root, [
115
+ "diff",
116
+ "--name-only",
117
+ baseline,
118
+ "HEAD",
119
+ "--",
120
+ scoped(repository, directory),
121
+ ]);
122
+ if (committed.ok && committed.out.length > 0) found.push(...committed.out.split("\n"));
123
+ const working = memoryGit(repository.root, [
124
+ "diff",
125
+ "--name-only",
126
+ "HEAD",
127
+ "--",
128
+ scoped(repository, directory),
129
+ ]);
130
+ if (working.ok && working.out.length > 0) found.push(...working.out.split("\n"));
131
+ const untracked = memoryGit(repository.root, [
132
+ "ls-files",
133
+ "--others",
134
+ "--exclude-standard",
135
+ "--",
136
+ scoped(repository, directory),
137
+ ]);
138
+ if (untracked.ok && untracked.out.length > 0) found.push(...untracked.out.split("\n"));
139
+ return found;
140
+ }
141
+
142
+ /** What has changed in a bot's memory since its last tidy commit. */
143
+ export function memoryTidyState(memoryDir: string, bot?: string): MemoryTidyState {
144
+ const repository = ensureRepository(memoryDir);
145
+ const baseline = lastTidyCommit(repository, memoryDir, bot);
146
+ const paths =
147
+ baseline === undefined
148
+ ? notesOnDisk(memoryDir)
149
+ : changedSince(repository, memoryDir, baseline)
150
+ .map((path) => notePath(repository, memoryDir, path))
151
+ .filter((path): path is string => path !== undefined);
152
+ const notes = [...new Set(paths.filter(isNote))].sort();
153
+ const index = join(memoryDir, "index.md");
154
+ const indexBytes = existsSync(index) ? Buffer.byteLength(readFileSync(index, "utf8"), "utf8") : 0;
155
+ return {
156
+ repository,
157
+ directory: memoryDir,
158
+ baseline,
159
+ since: baseline === undefined ? undefined : commitTime(repository, baseline),
160
+ notes,
161
+ indexBytes,
162
+ indexOver: indexBytes > MEMORY_INDEX_MAX,
163
+ };
164
+ }
165
+
166
+ /** The list items of an index; one line is one entry. */
167
+ export function indexEntries(text: string): string[] {
168
+ return text
169
+ .split("\n")
170
+ .map((line) => line.trim())
171
+ .filter((line) => /^[-*]\s+/.test(line));
172
+ }
173
+
174
+ function indexAt(repository: Repository, directory: string, commit: string): string {
175
+ const path = scoped(repository, directory);
176
+ const file = path === "." ? "index.md" : `${path}/index.md`;
177
+ const found = memoryGit(repository.root, ["show", `${commit}:${file}`]);
178
+ return found.ok ? found.out : "";
179
+ }
180
+
181
+ /** How many old index entries a rewrite drops, and whether that voids it. */
182
+ export function rewriteDrop(
183
+ repository: Repository,
184
+ directory: string,
185
+ baseline: string,
186
+ ): { readonly before: number; readonly removed: number; readonly voided: boolean } {
187
+ const before = indexEntries(indexAt(repository, directory, baseline));
188
+ if (before.length === 0) return { before: 0, removed: 0, voided: false };
189
+ const index = join(directory, "index.md");
190
+ const after = new Set(indexEntries(existsSync(index) ? readFileSync(index, "utf8") : ""));
191
+ const removed = before.filter((entry) => !after.has(entry)).length;
192
+ return {
193
+ before: before.length,
194
+ removed,
195
+ voided: removed > 0 && removed / before.length >= TIDY_MAX_DROP,
196
+ };
197
+ }
198
+
199
+ /** The old text with every line the rewrite added, and no line it removed. */
200
+ export function appendOnlyMerge(before: string, after: string): string {
201
+ if (before === after) return before;
202
+ const known = new Set(before.split("\n"));
203
+ const additions = after.split("\n").filter((line) => !known.has(line));
204
+ if (additions.length === 0) return before;
205
+ return `${before.endsWith("\n") || before.length === 0 ? before : `${before}\n`}${additions.join("\n")}`;
206
+ }
207
+
208
+ /**
209
+ * Puts a memory directory back to append only: a tracked file the run deleted
210
+ * comes back, and a changed one keeps its old lines and gains the new ones.
211
+ * Files the run added stay. Returns the files it rewrote.
212
+ */
213
+ export function applyAppendOnly(
214
+ repository: Repository,
215
+ directory: string,
216
+ baseline: string,
217
+ ): readonly string[] {
218
+ const listed = memoryGit(repository.root, [
219
+ "ls-tree",
220
+ "-r",
221
+ "--name-only",
222
+ baseline,
223
+ "--",
224
+ scoped(repository, directory),
225
+ ]);
226
+ if (!listed.ok) return [];
227
+ const rewritten: string[] = [];
228
+ for (const path of listed.out.split("\n")) {
229
+ if (path.length === 0) continue;
230
+ const shown = memoryGit(repository.root, ["show", `${baseline}:${path}`]);
231
+ if (!shown.ok) continue;
232
+ const before = shown.out;
233
+ const file = join(repository.root, ...path.split("/"));
234
+ const after = existsSync(file) ? readFileSync(file, "utf8") : undefined;
235
+ if (after === before) continue;
236
+ const next = after === undefined ? before : appendOnlyMerge(before, after);
237
+ if (next !== after) {
238
+ mkdirSync(dirname(file), { recursive: true });
239
+ writeFileSync(file, next);
240
+ rewritten.push(notePath(repository, directory, file) ?? path);
241
+ }
242
+ }
243
+ return rewritten.sort();
244
+ }
245
+
246
+ /** The tidy commit a chat made in the memory repository, if it made one. */
247
+ export function tidyCommitForChat(
248
+ repository: Repository,
249
+ directory: string,
250
+ chat: string,
251
+ ): string | undefined {
252
+ const escaped = chat.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
253
+ const found = memoryGit(repository.root, [
254
+ "log",
255
+ "-1",
256
+ "--format=%H",
257
+ "--extended-regexp",
258
+ "--grep",
259
+ `^tidy: bot .+, chat ${escaped}$`,
260
+ ]);
261
+ return found.ok && found.out.length > 0 ? found.out : undefined;
262
+ }
263
+
264
+ /** Where a tidy commit's run is read from: its memory directory and bot. */
265
+ export interface TidySummaryScope {
266
+ /** The memory directory the run changed; the repository's directory by default. */
267
+ readonly directory?: string | undefined;
268
+ /** The bot whose tidy this is; without it a commit must touch the directory. */
269
+ readonly bot?: string | undefined;
270
+ }
271
+
272
+ /**
273
+ * The tidy commit a run measured from: the latest tidy commit before `commit`,
274
+ * or undefined before the first one.
275
+ */
276
+ function previousTidyCommit(
277
+ repository: Repository,
278
+ directory: string,
279
+ commit: string,
280
+ bot?: string,
281
+ ): string | undefined {
282
+ const found = memoryGit(repository.root, [
283
+ "log",
284
+ "-1",
285
+ "--format=%H",
286
+ `${commit}^`,
287
+ `--grep=^${TIDY_SUBJECT}${bot === undefined ? "" : ` bot ${bot},`}`,
288
+ ...(bot === undefined ? ["--", scoped(repository, directory)] : []),
289
+ ]);
290
+ return found.ok && found.out.length > 0 ? found.out : undefined;
291
+ }
292
+
293
+ /** The diff stat of a run from its baseline, or from an empty tree before one. */
294
+ function runStat(
295
+ repository: Repository,
296
+ directory: string,
297
+ baseline: string | undefined,
298
+ commit: string,
299
+ ): string {
300
+ const paths = ["--", scoped(repository, directory)];
301
+ if (baseline !== undefined) {
302
+ return memoryGit(repository.root, ["diff", "--stat", baseline, commit, ...paths]).out;
303
+ }
304
+ const empty = memoryGit(repository.root, ["mktree"]);
305
+ return empty.ok && empty.out.length > 0
306
+ ? memoryGit(repository.root, ["diff", "--stat", empty.out, commit, ...paths]).out
307
+ : memoryGit(repository.root, ["show", "--stat", "--format=", commit, ...paths]).out;
308
+ }
309
+
310
+ /** A tidy commit's subject, whether it was voided, and its run's diff-stat line. */
311
+ export interface TidyCommitSummary {
312
+ readonly hash: string;
313
+ readonly subject: string;
314
+ readonly voided: boolean;
315
+ readonly changed: boolean;
316
+ readonly summary: string;
317
+ }
318
+
319
+ /**
320
+ * Reads what a tidy run did, for the tidy object's section or the notice. The
321
+ * stat runs from the commit the run measured from, so a chat's ordinary memory
322
+ * commit between the two is part of the run.
323
+ */
324
+ export function tidyCommitSummary(
325
+ repository: Repository,
326
+ commit: string,
327
+ scope: TidySummaryScope = {},
328
+ ): TidyCommitSummary {
329
+ const directory = scope.directory ?? repository.directory;
330
+ const body = memoryGit(repository.root, ["show", "-s", "--format=%s%n%b", commit]);
331
+ const baseline = previousTidyCommit(repository, directory, commit, scope.bot);
332
+ const stat = runStat(repository, directory, baseline, commit);
333
+ const lines = stat.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
334
+ const summary = lines.at(-1) ?? "No file statistics.";
335
+ return {
336
+ hash: commit,
337
+ subject: body.out.split("\n")[0] ?? "",
338
+ voided: body.out.includes("append only:"),
339
+ changed: /changed|insertion|deletion/.test(summary),
340
+ summary,
341
+ };
342
+ }