@hcflabs/pi-memory 0.0.0-stage → 9.2.11

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/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@hcflabs/pi-memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "9.2.11",
4
+ "description": "Auto-managed markdown memory for Pi: capped MEMORY.md/USER.md entry stores with frozen session snapshots.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "memory"
9
+ ],
10
+ "type": "module",
11
+ "engines": {
12
+ "node": ">=22.19.0"
13
+ },
14
+ "license": "MIT",
15
+ "files": [
16
+ "LICENSE",
17
+ "docs",
18
+ "extensions",
19
+ "src",
20
+ "README.md"
21
+ ],
22
+ "scripts": {
23
+ "test": "node --test test/*.test.ts",
24
+ "typecheck": "tsc --noEmit --allowImportingTsExtensions --target ES2022 --module NodeNext --moduleResolution NodeNext --skipLibCheck extensions/*.ts src/*.ts test/*.test.ts",
25
+ "pack:check": "npm pack --dry-run"
26
+ },
27
+ "dependencies": {
28
+ "@hcflabs/pi-ask-question": "^3.0.0",
29
+ "@hcflabs/pi-config-store": "^4.0.0",
30
+ "@hcflabs/pi-task-models": "^9.0.0",
31
+ "proper-lockfile": "^4.1.2"
32
+ },
33
+ "peerDependencies": {
34
+ "@earendil-works/pi-ai": "^1.3.0",
35
+ "@earendil-works/pi-coding-agent": "^1.3.0",
36
+ "@earendil-works/pi-tui": "^1.3.0",
37
+ "typebox": "^1.3.15"
38
+ },
39
+ "devDependencies": {
40
+ "@earendil-works/pi-ai": "1.3.0",
41
+ "@earendil-works/pi-coding-agent": "1.3.0",
42
+ "@earendil-works/pi-tui": "1.3.0",
43
+ "@types/proper-lockfile": "^4.1.4"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/hcflabs/pi-harness.git",
48
+ "directory": "extensions/pi-memory"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/hcflabs/pi-harness/issues"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "pi": {
57
+ "extensions": [
58
+ "./extensions/memory.ts"
59
+ ]
60
+ }
61
+ }
package/src/config.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { join } from "node:path";
2
+ import { createConfigStore, extensionConfigDir, field, parsers } from "@hcflabs/pi-config-store";
3
+
4
+ const EXTENSION_ID = "pi-memory";
5
+
6
+ export const DEFAULT_MEMORY_CHAR_LIMIT = 8800;
7
+ export const DEFAULT_USER_CHAR_LIMIT = 5500;
8
+
9
+ const charLimit = parsers.integer({ min: 1, max: 100_000 });
10
+
11
+ export function memoryConfigStore(agentDir?: string) {
12
+ return createConfigStore({
13
+ extensionId: EXTENSION_ID,
14
+ agentDir,
15
+ fields: {
16
+ // A default directory would read and write the wrong store, so an invalid one disables memory.
17
+ directory: field(parsers.absolutePath(), join(extensionConfigDir(EXTENSION_ID, agentDir), "memory"), { onInvalid: "disable" }),
18
+ memoryCharLimit: field(charLimit, DEFAULT_MEMORY_CHAR_LIMIT),
19
+ userCharLimit: field(charLimit, DEFAULT_USER_CHAR_LIMIT),
20
+ },
21
+ });
22
+ }
23
+
24
+ export type MemoryConfigStore = ReturnType<typeof memoryConfigStore>;
25
+ export type MemoryConfig = Extract<ReturnType<MemoryConfigStore["loadSync"]>, { status: "ok" }>["value"];
package/src/store.ts ADDED
@@ -0,0 +1,520 @@
1
+ import { createHash } from "node:crypto";
2
+ import { copyFile, lstat, mkdir, open, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+
5
+ export const ENTRY_DELIMITER: string = "\n§\n";
6
+ const RESERVED_FRAME_LINE = /^\s*(?:═{3,}|MEMORY \(your personal notes|USER PROFILE \(who the user is)/;
7
+
8
+ export function isReservedFrameLine(line: string): boolean {
9
+ return RESERVED_FRAME_LINE.test(line);
10
+ }
11
+
12
+ export type Target = "memory" | "user";
13
+
14
+ interface StoreConfig {
15
+ directory: string;
16
+ target: Target;
17
+ limit: number;
18
+ /** Called before every rewrite of an existing file; store copies the old file there. */
19
+ backupPath?: string;
20
+ /** Test seam: rename implementation. Defaults to fs.rename. */
21
+ renameFn?: (from: string, to: string) => Promise<void>;
22
+ /** Test seam: stat implementation for persistence-time checks. Defaults to fs.stat. */
23
+ statFn?: (path: string) => Promise<import("node:fs").Stats>;
24
+ }
25
+
26
+ type LoadResult =
27
+ | { entries: string[]; state: "ok"; raw: string }
28
+ | { entries: []; state: "absent"; raw: "" }
29
+ | { entries: []; state: "unreadable"; conflictWarning: string }
30
+ | { entries: []; state: "oversized"; conflictWarning: string };
31
+
32
+ /** An operation after the memory tool has validated its structure and content. */
33
+ export type MemoryOperation =
34
+ | { action: "add"; content: string }
35
+ | { action: "replace"; old_text: string; content: string }
36
+ | { action: "remove"; old_text: string };
37
+
38
+ /** Refuse to inject snapshots or accept serialized mutations above this size. */
39
+ export const MAX_FILE_BYTES = 1_000_000;
40
+ export const MAX_BATCH_OPERATIONS = 100;
41
+
42
+ type FileState =
43
+ | { kind: "ok"; raw: string }
44
+ | { kind: "absent" }
45
+ | { kind: "unreadable"; confirmedPresent: boolean; reason?: string }
46
+ | { kind: "oversized"; bytes: number };
47
+
48
+ type Result = {
49
+ success: boolean;
50
+ message?: string;
51
+ error?: string;
52
+ usage?: string;
53
+ entryCount?: number;
54
+ writtenEntries?: string[];
55
+ currentEntries?: string[];
56
+ matches?: string[];
57
+ };
58
+
59
+ const PREVIEW_WIDTH = 80;
60
+ const MAX_PREVIEW_CHARS = 1500;
61
+
62
+ export function isEnoent(error: unknown): boolean {
63
+ return !!error && typeof error === "object" && "code" in error && error.code === "ENOENT";
64
+ }
65
+
66
+ function previews(entries: string[]): string[] {
67
+ let chars = 0;
68
+ const shown: string[] = [];
69
+ for (const entry of entries) {
70
+ if (chars + PREVIEW_WIDTH > MAX_PREVIEW_CHARS) break;
71
+ shown.push(entry.length > PREVIEW_WIDTH ? `${entry.slice(0, PREVIEW_WIDTH)}...` : entry);
72
+ chars += PREVIEW_WIDTH;
73
+ }
74
+ return shown;
75
+ }
76
+
77
+ export function usage(current: number, limit: number): string {
78
+ const pct = Math.min(100, Math.floor((current / limit) * 100));
79
+ return `${pct}% — ${current.toLocaleString()}/${limit.toLocaleString()} chars`;
80
+ }
81
+
82
+ /**
83
+ * Binding normalization order: strip BOM -> all line terminators to LF -> trim.
84
+ * Delimiter validation, parsing, budgeting, and matching all operate on
85
+ * normalized text so "a\r\n§\r\nb" cannot smuggle a delimiter past us and
86
+ * CR/LF/NEL/VT/FF/U+2028/U+2029 cannot smuggle fake frame lines past line-based
87
+ * filters. ponytail: NFKC/zero-width lookalike spoofing is NOT handled — the
88
+ * frame headers are advisory context, not a security boundary; revisit only if
89
+ * entries start coming from untrusted writers.
90
+ */
91
+ export function normalizeEntry(raw: string): string {
92
+ return raw.replace(/^\uFEFF/, "").replace(/\r\n?|[\u2028\u2029\u0085\u000B\u000C]/g, "\n").trim();
93
+ }
94
+
95
+ function parseEntries(raw: string): string[] {
96
+ const text = normalizeEntry(raw);
97
+ if (!text) return [];
98
+ // Deduplicate, preserving order and first occurrence.
99
+ return [...new Set(text.split(ENTRY_DELIMITER).map((e) => e.trim()).filter(Boolean))];
100
+ }
101
+
102
+ export class MemoryStore {
103
+ readonly path: string;
104
+ private readonly directory: string;
105
+ private readonly limit: number;
106
+ private readonly backupPath?: string;
107
+ private readonly renameFn: NonNullable<StoreConfig["renameFn"]>;
108
+ private readonly statFn: NonNullable<StoreConfig["statFn"]>;
109
+ private entries: string[] = [];
110
+ private consolidationFailures = 0;
111
+ // The file was observed on disk this session — used to detect unexpected
112
+ // mid-session disappearance before a mutation rewrites from an empty view.
113
+ private observedExisting = false;
114
+ // Metadata and content digest of the last successfully loaded file.
115
+ private loadedFingerprint?: { mtimeMs: number; size: number; digest: string };
116
+
117
+ constructor(config: StoreConfig) {
118
+ this.directory = config.directory;
119
+ this.path = join(config.directory, config.target === "user" ? "USER.md" : "MEMORY.md");
120
+ this.limit = config.limit;
121
+ this.backupPath = config.backupPath;
122
+ this.renameFn = config.renameFn ?? rename;
123
+ this.statFn = config.statFn ?? stat;
124
+ }
125
+
126
+ private charCount(): number {
127
+ return this.entries.join(ENTRY_DELIMITER).length;
128
+ }
129
+
130
+ private currentUsage(): string {
131
+ return usage(this.charCount(), this.limit);
132
+ }
133
+
134
+ private successResponse(message?: string, writtenEntries: string[] = []): Result {
135
+ this.resetOnSuccess();
136
+ return {
137
+ success: true,
138
+ message,
139
+ usage: this.currentUsage(),
140
+ entryCount: this.entries.length,
141
+ writtenEntries,
142
+ };
143
+ }
144
+
145
+ private consolidationFailure(error: string, resultUsage?: string): Result {
146
+ return {
147
+ success: false,
148
+ error,
149
+ currentEntries: previews(this.entries),
150
+ usage: resultUsage ?? this.currentUsage(),
151
+ };
152
+ }
153
+
154
+ /**
155
+ * Track consecutive consolidation failures. After 3, the model is told to
156
+ * stop retrying ({ done: true }); a successful write resets the count.
157
+ */
158
+ incrementFailure(): { done: boolean } {
159
+ this.consolidationFailures += 1;
160
+ return { done: this.consolidationFailures >= 3 };
161
+ }
162
+
163
+ resetOnSuccess(): void {
164
+ this.consolidationFailures = 0;
165
+ }
166
+
167
+ async load(): Promise<LoadResult> {
168
+ const file = await this.readFileState();
169
+ if (file.kind === "unreadable") {
170
+ return {
171
+ entries: [],
172
+ state: "unreadable",
173
+ conflictWarning: file.reason ?? (file.confirmedPresent
174
+ ? `${this.path} exists but could not be read; refusing to serve a possibly-wrong view.`
175
+ : `${this.path} could not be read and its presence could not be confirmed; refusing to serve a possibly-wrong view.`),
176
+ };
177
+ }
178
+ if (file.kind === "oversized") {
179
+ return {
180
+ entries: [],
181
+ state: "oversized",
182
+ conflictWarning: `${this.path} is ${file.bytes.toLocaleString()} bytes, over the ${MAX_FILE_BYTES.toLocaleString()}-byte injection limit; refusing to serve it. Consolidate the file manually.`,
183
+ };
184
+ }
185
+ if (file.kind === "absent" && this.observedExisting) {
186
+ return {
187
+ entries: [],
188
+ state: "unreadable",
189
+ conflictWarning: `${this.path} existed earlier this session but has disappeared; refusing to serve an empty view. Restore it and retry.`,
190
+ };
191
+ }
192
+ if (file.kind === "ok") return { entries: parseEntries(file.raw), state: "ok", raw: file.raw };
193
+ return { entries: [], state: "absent", raw: "" };
194
+ }
195
+
196
+ private async digestFile(): Promise<string> {
197
+ const handle = await open(this.path, "r");
198
+ try {
199
+ const hash = createHash("sha256");
200
+ const buffer = Buffer.alloc(64 * 1024);
201
+ let total = 0;
202
+ for (;;) {
203
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
204
+ if (bytesRead === 0) return hash.digest("base64url");
205
+ total += bytesRead;
206
+ if (total > MAX_FILE_BYTES) throw new Error(`${this.path} grew over the ${MAX_FILE_BYTES.toLocaleString()}-byte limit during mutation.`);
207
+ hash.update(buffer.subarray(0, bytesRead));
208
+ }
209
+ } finally {
210
+ await handle.close();
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Returns file state: "absent" for a missing file, "unreadable" when it
216
+ * could not be read, and "oversized" when it exceeds MAX_FILE_BYTES.
217
+ * Unreadable states say whether this read proved the file existed. Callers
218
+ * must abort on unreadable/oversized rather than assume an empty store.
219
+ */
220
+ private async readFileState(): Promise<FileState> {
221
+ // Bounded, EOF-complete read: at most MAX_FILE_BYTES + 1 bytes leave the
222
+ // filesystem (so a huge synced file can't exhaust memory), and we keep
223
+ // reading until EOF so a short read from a network/synced filesystem can
224
+ // never be mistaken for the whole file.
225
+ let handle: import("node:fs/promises").FileHandle | undefined;
226
+ let confirmedPresent = false;
227
+ try {
228
+ // Symlinked store files are rejected before anything follows the link:
229
+ // tmp+rename would replace the link itself and silently disconnect
230
+ // writes from the intended synced target.
231
+ let ls: import("node:fs").Stats | undefined;
232
+ try {
233
+ ls = await lstat(this.path);
234
+ } catch (error) {
235
+ if (!isEnoent(error)) return { kind: "unreadable", confirmedPresent: false };
236
+ }
237
+ if (ls) {
238
+ confirmedPresent = true;
239
+ this.observedExisting = true;
240
+ }
241
+ if (ls?.isSymbolicLink()) {
242
+ return {
243
+ kind: "unreadable",
244
+ confirmedPresent: true,
245
+ reason: `${this.path} is a symlink; symlinked store files are not supported because atomic rewrites replace the link. Point the memory directory at real files.`,
246
+ };
247
+ }
248
+ handle = await open(this.path, "r");
249
+ confirmedPresent = true;
250
+ this.observedExisting = true;
251
+ const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
252
+ let total = 0;
253
+ for (;;) {
254
+ if (total > MAX_FILE_BYTES) return { kind: "oversized", bytes: total };
255
+ const { bytesRead } = await handle.read(buffer, total, buffer.length - total, null);
256
+ total += bytesRead;
257
+ if (bytesRead === 0) break; // EOF
258
+ }
259
+ // Fatal decode: invalid UTF-8 counts as unreadable — a lossy replacement
260
+ // view could get persisted back over the real bytes.
261
+ const raw = new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, total));
262
+ // Fingerprint for the pre-rename change check: an external sync that
263
+ // lands V2 between this read and persist must not be silently replaced
264
+ // by V1-plus-mutation.
265
+ try {
266
+ const st = await this.statFn(this.path);
267
+ this.loadedFingerprint = {
268
+ mtimeMs: st.mtimeMs,
269
+ size: st.size,
270
+ digest: createHash("sha256").update(buffer.subarray(0, total)).digest("base64url"),
271
+ };
272
+ } catch {
273
+ this.loadedFingerprint = undefined;
274
+ }
275
+ return { kind: "ok", raw };
276
+ } catch (error) {
277
+ if (isEnoent(error)) {
278
+ // ENOENT on the FILE is "absent" only if the configured directory
279
+ // itself still exists — a vanished synced/mounted directory must not
280
+ // be mistaken for an empty store and rewritten divergently.
281
+ try {
282
+ await stat(this.directory);
283
+ return { kind: "absent" };
284
+ } catch {
285
+ return { kind: "unreadable", confirmedPresent };
286
+ }
287
+ }
288
+ return { kind: "unreadable", confirmedPresent };
289
+ } finally {
290
+ await handle?.close().catch(() => {});
291
+ }
292
+ }
293
+
294
+ /** Re-read from disk, returning the exact write-blocking failure directly. */
295
+ private async reload(): Promise<Result | undefined> {
296
+ const loaded = await this.load();
297
+ if (loaded.state === "unreadable" || loaded.state === "oversized") {
298
+ return { success: false, error: loaded.conflictWarning };
299
+ }
300
+ if (loaded.state === "ok" && !this.loadedFingerprint) {
301
+ return {
302
+ success: false,
303
+ error: `${this.path} was read but could not be fingerprinted; refusing to write without change detection. Fix the file and retry — nothing was changed.`,
304
+ };
305
+ }
306
+ this.entries = loaded.entries;
307
+ }
308
+
309
+ private async persist(): Promise<void> {
310
+ await mkdir(this.directory, { recursive: true });
311
+ if (this.backupPath) {
312
+ // Recreate the backup parent so a cleaned-up backup directory can't be
313
+ // misread as "source absent" and silently skip the promised backup.
314
+ await mkdir(dirname(this.backupPath), { recursive: true });
315
+ try {
316
+ await copyFile(this.path, this.backupPath);
317
+ } catch (error) {
318
+ if (!isEnoent(error)) throw error;
319
+ // Backup dir now exists, so ENOENT means the SOURCE vanished after
320
+ // reload saw it — same divergence hazard as mid-session disappearance;
321
+ // never proceed from the stale view.
322
+ if (this.observedExisting) {
323
+ throw new Error(`${this.path} vanished before its backup could be written; aborting to avoid a divergent store.`);
324
+ }
325
+ }
326
+ }
327
+ const content = this.entries.join(ENTRY_DELIMITER);
328
+ const tmp = join(dirname(this.path), `.mem_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2)}`);
329
+ try {
330
+ // Preserve restrictive modes/ACLs across inode replacement: default
331
+ // umask would otherwise turn a 0600 USER.md into 0644.
332
+ let mode: number | undefined;
333
+ try {
334
+ mode = (await stat(this.path)).mode & 0o777;
335
+ } catch (error) {
336
+ if (!isEnoent(error)) throw error;
337
+ }
338
+ await writeFile(tmp, content, mode === undefined ? "utf-8" : { encoding: "utf-8", mode });
339
+ // A creation-assumed write (reload saw the file absent) must not clobber
340
+ // a file that appeared meanwhile (sync race): re-check just before the
341
+ // rename, as close to it as possible.
342
+ if (!this.observedExisting) {
343
+ try {
344
+ await this.statFn(this.path);
345
+ throw new Error(`${this.path} appeared during this mutation (likely sync); retry to merge its content.`);
346
+ } catch (error) {
347
+ if (!isEnoent(error)) throw error;
348
+ }
349
+ }
350
+ // An existing store must not be replaced if the on-disk version changed
351
+ // since reload (external sync landed V2 after we read V1): compare
352
+ // fingerprint immediately before the rename.
353
+ if (this.observedExisting && this.loadedFingerprint) {
354
+ try {
355
+ const current = await this.statFn(this.path);
356
+ if (current.mtimeMs !== this.loadedFingerprint.mtimeMs || current.size !== this.loadedFingerprint.size
357
+ || await this.digestFile() !== this.loadedFingerprint.digest) {
358
+ throw new Error(`${this.path} changed during this mutation (likely sync); retry to merge its content.`);
359
+ }
360
+ } catch (error) {
361
+ if (isEnoent(error)) {
362
+ throw new Error(`${this.path} disappeared during this mutation; retry after restoring it.`);
363
+ }
364
+ throw error;
365
+ }
366
+ }
367
+ try {
368
+ await this.renameFn(tmp, this.path);
369
+ } catch (error) {
370
+ if (isEnoent(error)) throw new Error(`${this.path} disappeared during this mutation; retry after restoring it.`);
371
+ throw error;
372
+ }
373
+ // The store now exists on disk; a later mid-session disappearance is
374
+ // unexpected and must abort, not rewrite from the in-memory view.
375
+ this.observedExisting = true;
376
+ } finally {
377
+ await rm(tmp, { force: true }).catch(() => {});
378
+ }
379
+ }
380
+
381
+ private static ambiguousError(oldText: string, matches: string[]): Result {
382
+ return {
383
+ success: false,
384
+ error: `Multiple entries matched '${oldText}'. Be more specific.`,
385
+ matches: previews(matches),
386
+ };
387
+ }
388
+
389
+ /**
390
+ * Resolve substring matches against entries. Entries are duplicate-free by
391
+ * invariant (dedupe on load + after every mutation), so multiple matches
392
+ * are always distinct entries.
393
+ */
394
+ private static resolveMatch(entries: string[], oldText: string): ["missing"] | ["ambiguous", string[]] | [number] {
395
+ const matches = entries.map((e, i) => (e.includes(oldText) ? i : -1)).filter((i) => i >= 0);
396
+ if (matches.length === 0) return ["missing"];
397
+ if (matches.length > 1) {
398
+ return ["ambiguous", matches.map((i) => entries[i]!)];
399
+ }
400
+ return [matches[0]!];
401
+ }
402
+
403
+ async apply(operation: MemoryOperation): Promise<Result> {
404
+ const failure = await this.reload();
405
+ if (failure) return failure;
406
+ const entries = this.entries;
407
+
408
+ if (operation.action === "add") {
409
+ const text = normalizeEntry(operation.content);
410
+ if (entries.includes(text)) {
411
+ return this.successResponse("Entry already exists (no duplicate added).", [text]);
412
+ }
413
+
414
+ const newTotal = [...entries, text].join(ENTRY_DELIMITER).length;
415
+ if (newTotal > this.limit) {
416
+ return this.consolidationFailure(
417
+ `Memory at ${this.charCount().toLocaleString()}/${this.limit.toLocaleString()} chars. `
418
+ + `Adding this entry (${text.length} chars) would exceed the limit. Consolidate now: use 'replace' to merge `
419
+ + `overlapping entries into shorter ones or 'remove' stale or less important entries (see current_entries below), `
420
+ + `then retry this add — all in this turn.`,
421
+ );
422
+ }
423
+
424
+ entries.push(text);
425
+ await this.persist();
426
+ return this.successResponse("Entry added.", [text]);
427
+ }
428
+
429
+ const oldText = normalizeEntry(operation.old_text);
430
+ const resolved = MemoryStore.resolveMatch(entries, oldText);
431
+ if (resolved[0] === "missing") {
432
+ return this.consolidationFailure(
433
+ `No entry matched '${oldText}'. Check current_entries below and retry with the exact text of the entry you want to ${operation.action}.`,
434
+ );
435
+ }
436
+ if (resolved[0] === "ambiguous") return MemoryStore.ambiguousError(oldText, resolved[1]);
437
+
438
+ if (operation.action === "remove") {
439
+ entries.splice(resolved[0], 1);
440
+ await this.persist();
441
+ return this.successResponse("Entry removed.");
442
+ }
443
+
444
+ const text = normalizeEntry(operation.content);
445
+ const testEntries = [...entries];
446
+ testEntries[resolved[0]] = text;
447
+ // A replace can create a duplicate; dedupe order-preserving before budget.
448
+ const deduped = [...new Set(testEntries)];
449
+ const newTotal = deduped.join(ENTRY_DELIMITER).length;
450
+ if (newTotal > this.limit) {
451
+ return this.consolidationFailure(
452
+ `Replacement would put memory at ${newTotal.toLocaleString()}/${this.limit.toLocaleString()} chars. `
453
+ + `Shorten the new content, or 'remove' other stale or less important entries to make room `
454
+ + `(see current_entries below), then retry — all in this turn.`,
455
+ );
456
+ }
457
+
458
+ this.entries = deduped;
459
+ await this.persist();
460
+ return this.successResponse("Entry replaced.", [text]);
461
+ }
462
+
463
+ /**
464
+ * Apply validated add/replace/remove operations atomically against the FINAL
465
+ * budget: intermediate overflow is fine, only the end state is checked.
466
+ */
467
+ async applyBatch(operations: [MemoryOperation, ...MemoryOperation[]]): Promise<Result> {
468
+ const failure = await this.reload();
469
+ if (failure) return failure;
470
+
471
+ let working = [...this.entries];
472
+ const writtenEntries = new Set<string>();
473
+ const fail = (message: string): Result =>
474
+ this.consolidationFailure(`${message} No operations were applied (batch is all-or-nothing).`);
475
+
476
+ for (let i = 0; i < operations.length; i++) {
477
+ const operation = operations[i]!;
478
+ const pos = `Operation ${i + 1} (${operation.action})`;
479
+
480
+ if (operation.action === "add") {
481
+ const content = normalizeEntry(operation.content);
482
+ writtenEntries.add(content);
483
+ if (working.includes(content)) continue; // idempotent duplicate
484
+ working.push(content);
485
+ continue;
486
+ }
487
+
488
+ const oldText = normalizeEntry(operation.old_text);
489
+ const resolved = MemoryStore.resolveMatch(working, oldText);
490
+ if (resolved[0] === "missing") return fail(`${pos}: no entry matched '${oldText}'.`);
491
+ if (resolved[0] === "ambiguous") return fail(`${pos}: '${oldText}' matched multiple distinct entries -- be more specific.`);
492
+
493
+ if (operation.action === "remove") {
494
+ working.splice(resolved[0], 1);
495
+ continue;
496
+ }
497
+
498
+ const content = normalizeEntry(operation.content);
499
+ working[resolved[0]] = content;
500
+ writtenEntries.add(content);
501
+ // A replace can create a duplicate; dedupe order-preserving before later ops/budget.
502
+ working = [...new Set(working)];
503
+ }
504
+
505
+ const newTotal = working.join(ENTRY_DELIMITER).length;
506
+ if (newTotal > this.limit) {
507
+ const current = this.charCount();
508
+ return this.consolidationFailure(
509
+ `After applying all ${operations.length} operations, memory would be at ${newTotal.toLocaleString()}/`
510
+ + `${this.limit.toLocaleString()} chars -- over the limit. Remove or shorten more entries in the same batch `
511
+ + `(see current_entries below), then retry.`,
512
+ `${current.toLocaleString()}/${this.limit.toLocaleString()}`,
513
+ );
514
+ }
515
+
516
+ this.entries = working;
517
+ await this.persist();
518
+ return this.successResponse(`Applied ${operations.length} operation(s).`, [...writtenEntries].filter((entry) => working.includes(entry)));
519
+ }
520
+ }