@useavalon/caelence-agent 0.2.2 → 0.2.3-canary.1

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.
@@ -0,0 +1,24 @@
1
+ import type { MemoryFact } from "./store.ts";
2
+
3
+ export function formatRetrievedMemory(facts: MemoryFact[]): string {
4
+ if (facts.length === 0) return "";
5
+ const bullets = facts.map((fact) => `- ${fact.text}`).join("\n");
6
+ return `These are stored prefs from earlier chats. Use them to answer personal questions (where they live, favorites, tools they prefer). Do not mention Memory unless the user asks.\n${bullets}`;
7
+ }
8
+
9
+ export function formatMemoryList(input: { enabled: boolean; facts: MemoryFact[] }): string {
10
+ if (!input.enabled && input.facts.length === 0) {
11
+ return "Memory is off. /memory on remembers prefs and project decisions across chats.";
12
+ }
13
+ const state = input.enabled ? "on" : "off";
14
+ if (input.facts.length === 0) {
15
+ return `Memory is ${state}. No facts yet.`;
16
+ }
17
+ const rows = input.facts.map(
18
+ (fact, index) => `${index + 1} ${fact.scope.padEnd(7)} ${fact.text}`,
19
+ );
20
+ const hint = input.enabled
21
+ ? "/memory delete 1 · /memory pin 1 · /memory off"
22
+ : "Facts stay on disk. /memory on to use them.";
23
+ return [`Memory ${state} · ${input.facts.length} facts`, ...rows, hint].join("\n");
24
+ }
@@ -0,0 +1,191 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import {
6
+ addFacts,
7
+ deleteFact,
8
+ isFactPinned,
9
+ isSecretLike,
10
+ listFacts,
11
+ matchFact,
12
+ pinFact,
13
+ searchFacts,
14
+ stripPinnedText,
15
+ unpinFact,
16
+ } from "./store.ts";
17
+
18
+ async function withDirs() {
19
+ const cwd = await mkdtemp(join(tmpdir(), "harness-mem-"));
20
+ const home = await mkdtemp(join(tmpdir(), "harness-mem-home-"));
21
+ const env = { HARNESS_HOME: home };
22
+ return {
23
+ cwd,
24
+ env,
25
+ async close() {
26
+ await rm(cwd, { recursive: true, force: true });
27
+ await rm(home, { recursive: true, force: true });
28
+ },
29
+ };
30
+ }
31
+
32
+ describe("memory store", () => {
33
+ test("adds user and project facts and hash-dedups", async () => {
34
+ const ctx = await withDirs();
35
+ try {
36
+ const first = addFacts(
37
+ ctx.cwd,
38
+ [
39
+ { text: "Prefer bun over npm", scope: "user" },
40
+ { text: "Tests live next to the source", scope: "project" },
41
+ ],
42
+ ctx.env,
43
+ );
44
+ expect(first).toHaveLength(2);
45
+ const again = addFacts(ctx.cwd, [{ text: "prefer bun over npm", scope: "user" }], ctx.env);
46
+ expect(again).toHaveLength(0);
47
+ const listed = listFacts(ctx.cwd, ctx.env);
48
+ expect(listed.map((fact) => fact.text)).toEqual([
49
+ "Prefer bun over npm",
50
+ "Tests live next to the source",
51
+ ]);
52
+ expect(listed[0]?.scope).toBe("user");
53
+ expect(listed[1]?.scope).toBe("project");
54
+ } finally {
55
+ await ctx.close();
56
+ }
57
+ });
58
+
59
+ test("drops secrets and tiny noise", async () => {
60
+ expect(isSecretLike("OPENROUTER_API_KEY=sk-or-v1-abcdefgh")).toBe(true);
61
+ const ctx = await withDirs();
62
+ try {
63
+ const added = addFacts(
64
+ ctx.cwd,
65
+ [
66
+ { text: "key=sk-or-v1-abcdefgh", scope: "user" },
67
+ { text: "short", scope: "user" },
68
+ { text: "Use the instrument blue for action color", scope: "user" },
69
+ ],
70
+ ctx.env,
71
+ );
72
+ expect(added.map((fact) => fact.text)).toEqual(["Use the instrument blue for action color"]);
73
+ } finally {
74
+ await ctx.close();
75
+ }
76
+ });
77
+
78
+ test("searches by overlap and recency", async () => {
79
+ const ctx = await withDirs();
80
+ try {
81
+ addFacts(
82
+ ctx.cwd,
83
+ [
84
+ { text: "Prefer vim keybindings in the terminal", scope: "user" },
85
+ { text: "The desktop window talks to a loopback bridge", scope: "project" },
86
+ { text: "Prefer bun over npm for installs", scope: "user" },
87
+ ],
88
+ ctx.env,
89
+ );
90
+ const hits = searchFacts(ctx.cwd, "which package manager for installs", 5, ctx.env);
91
+ expect(hits[0]?.text).toContain("bun over npm");
92
+ expect(searchFacts(ctx.cwd, "loopback bridge", 3, ctx.env)[0]?.text).toContain(
93
+ "loopback bridge",
94
+ );
95
+ const personal = searchFacts(ctx.cwd, "whats my favorite club", 10, ctx.env);
96
+ expect(personal.map((fact) => fact.text)).toEqual(
97
+ expect.arrayContaining([
98
+ "Prefer vim keybindings in the terminal",
99
+ "Prefer bun over npm for installs",
100
+ ]),
101
+ );
102
+ } finally {
103
+ await ctx.close();
104
+ }
105
+ });
106
+
107
+ test("ranks a leftover name when a personal question has no matching noun", async () => {
108
+ const ctx = await withDirs();
109
+ try {
110
+ addFacts(
111
+ ctx.cwd,
112
+ [
113
+ { text: "Lives in Riverton.", scope: "user" },
114
+ { text: "Enjoys football, beer, and walking.", scope: "user" },
115
+ { text: "Likes Northgate (frequent destination or hometown connection).", scope: "user" },
116
+ ],
117
+ ctx.env,
118
+ );
119
+ const club = searchFacts(ctx.cwd, "whats my favorite club", 10, ctx.env);
120
+ expect(club[0]?.text).toContain("Northgate");
121
+ expect(club.map((fact) => fact.text).join("\n")).toContain("football");
122
+ const home = searchFacts(ctx.cwd, "where do i live", 10, ctx.env);
123
+ expect(home[0]?.text).toContain("Riverton");
124
+ addFacts(ctx.cwd, [{ text: "Likes Westfield on weekends.", scope: "user" }], ctx.env);
125
+ const ambiguous = searchFacts(ctx.cwd, "favourite football club", 10, ctx.env);
126
+ expect(ambiguous[0]?.text).toContain("football");
127
+ expect(ambiguous.some((fact) => fact.text.includes("Northgate"))).toBe(true);
128
+ expect(ambiguous.some((fact) => fact.text.includes("Westfield"))).toBe(true);
129
+ } finally {
130
+ await ctx.close();
131
+ }
132
+ });
133
+
134
+ test("deletes by id and matches list index", async () => {
135
+ const ctx = await withDirs();
136
+ try {
137
+ addFacts(
138
+ ctx.cwd,
139
+ [
140
+ { text: "Prefer bun over npm", scope: "user" },
141
+ { text: "Keep desktop chrome compact", scope: "project" },
142
+ ],
143
+ ctx.env,
144
+ );
145
+ const facts = listFacts(ctx.cwd, ctx.env);
146
+ expect(matchFact(facts, "2")?.text).toContain("desktop chrome");
147
+ expect(deleteFact(ctx.cwd, facts[0]?.id ?? "", ctx.env)?.text).toContain("bun");
148
+ expect(listFacts(ctx.cwd, ctx.env)).toHaveLength(1);
149
+ } finally {
150
+ await ctx.close();
151
+ }
152
+ });
153
+
154
+ test("pins a fact onto AGENTS.md", async () => {
155
+ const ctx = await withDirs();
156
+ try {
157
+ const [fact] = addFacts(
158
+ ctx.cwd,
159
+ [{ text: "Do not add product telemetry", scope: "project" }],
160
+ ctx.env,
161
+ );
162
+ const pinned = pinFact(ctx.cwd, fact!, "AGENTS.md", ctx.env);
163
+ expect("path" in pinned).toBe(true);
164
+ if ("path" in pinned) {
165
+ expect(await readFile(pinned.path, "utf8")).toContain("Do not add product telemetry");
166
+ }
167
+ const again = pinFact(ctx.cwd, fact!, "AGENTS.md", ctx.env);
168
+ expect("path" in again).toBe(true);
169
+ const body = await readFile(join(ctx.cwd, "AGENTS.md"), "utf8");
170
+ expect(body.match(/Do not add product telemetry/g)?.length).toBe(1);
171
+ expect(isFactPinned(ctx.cwd, fact!, "AGENTS.md", ctx.env)).toBe(true);
172
+ const unpinned = unpinFact(ctx.cwd, fact!, "AGENTS.md", ctx.env);
173
+ expect(unpinned).toEqual({ path: join(ctx.cwd, "AGENTS.md"), removed: true });
174
+ expect(isFactPinned(ctx.cwd, fact!, "AGENTS.md", ctx.env)).toBe(false);
175
+ expect(await readFile(join(ctx.cwd, "AGENTS.md"), "utf8")).not.toContain(
176
+ "Do not add product telemetry",
177
+ );
178
+ } finally {
179
+ await ctx.close();
180
+ }
181
+ });
182
+
183
+ test("stripPinnedText only drops a standalone copy of the fact", () => {
184
+ expect(stripPinnedText("# Agents\n\nDo not add telemetry\n", "Do not add telemetry")).toBe(
185
+ "# Agents\n",
186
+ );
187
+ expect(stripPinnedText("please Do not add telemetry in CI\n", "Do not add telemetry")).toBe(
188
+ undefined,
189
+ );
190
+ });
191
+ });
@@ -0,0 +1,382 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { newId } from "../core/ids.ts";
5
+ import { userInstructionsPath } from "../core/instructions.ts";
6
+ import { harnessHome } from "../desktop/secrets.ts";
7
+
8
+ export type MemoryScope = "user" | "project";
9
+
10
+ export interface MemoryFact {
11
+ id: string;
12
+ hash: string;
13
+ text: string;
14
+ scope: MemoryScope;
15
+ createdAt: string;
16
+ sessionId?: string;
17
+ }
18
+
19
+ interface FactsFile {
20
+ facts: MemoryFact[];
21
+ }
22
+
23
+ const STOPWORDS = new Set([
24
+ "the",
25
+ "and",
26
+ "for",
27
+ "with",
28
+ "this",
29
+ "that",
30
+ "from",
31
+ "you",
32
+ "your",
33
+ "are",
34
+ "was",
35
+ "were",
36
+ "have",
37
+ "has",
38
+ "not",
39
+ "but",
40
+ "use",
41
+ "using",
42
+ ]);
43
+
44
+ const QUESTION_TOKENS = new Set(["what", "whats", "where", "who", "which", "how", "when"]);
45
+
46
+ export function normalizeFactText(raw: string): string {
47
+ return raw.replace(/\s+/g, " ").trim();
48
+ }
49
+
50
+ export function factHash(text: string): string {
51
+ return createHash("sha256").update(text.toLowerCase()).digest("hex").slice(0, 16);
52
+ }
53
+
54
+ export function isSecretLike(text: string): boolean {
55
+ if (/\bsk-[a-z0-9_-]{8,}\b/i.test(text)) return true;
56
+ if (/\b(api[_-]?key|secret|password|token|bearer)\b\s*[:=]/i.test(text)) return true;
57
+ if (/\beyJ[a-zA-Z0-9_-]{20,}\./.test(text)) return true;
58
+ return false;
59
+ }
60
+
61
+ export function userMemoryPath(env: Record<string, string | undefined> = process.env): string {
62
+ return resolve(harnessHome(env), "memory", "facts.json");
63
+ }
64
+
65
+ export function projectMemoryPath(cwd: string): string {
66
+ return resolve(cwd, ".harness", "memory", "facts.json");
67
+ }
68
+
69
+ function readFactsFile(path: string): MemoryFact[] {
70
+ if (!existsSync(path)) return [];
71
+ try {
72
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<FactsFile>;
73
+ return Array.isArray(parsed.facts) ? parsed.facts.filter(isMemoryFact) : [];
74
+ } catch {
75
+ return [];
76
+ }
77
+ }
78
+
79
+ function writeFactsFile(path: string, facts: MemoryFact[]): void {
80
+ mkdirSync(resolve(path, ".."), { recursive: true });
81
+ writeFileSync(path, `${JSON.stringify({ facts }, null, "\t")}\n`);
82
+ }
83
+
84
+ function isMemoryFact(value: unknown): value is MemoryFact {
85
+ if (!value || typeof value !== "object") return false;
86
+ const fact = value as Partial<MemoryFact>;
87
+ return (
88
+ typeof fact.id === "string" &&
89
+ typeof fact.hash === "string" &&
90
+ typeof fact.text === "string" &&
91
+ (fact.scope === "user" || fact.scope === "project") &&
92
+ typeof fact.createdAt === "string"
93
+ );
94
+ }
95
+
96
+ function pathForScope(
97
+ cwd: string,
98
+ scope: MemoryScope,
99
+ env: Record<string, string | undefined> = process.env,
100
+ ): string {
101
+ return scope === "user" ? userMemoryPath(env) : projectMemoryPath(cwd);
102
+ }
103
+
104
+ export function listFacts(
105
+ cwd: string,
106
+ env: Record<string, string | undefined> = process.env,
107
+ ): MemoryFact[] {
108
+ return [...readFactsFile(userMemoryPath(env)), ...readFactsFile(projectMemoryPath(cwd))];
109
+ }
110
+
111
+ export function addFacts(
112
+ cwd: string,
113
+ incoming: Array<{ text: string; scope?: MemoryScope; sessionId?: string }>,
114
+ env: Record<string, string | undefined> = process.env,
115
+ ): MemoryFact[] {
116
+ const known = new Set(listFacts(cwd, env).map((fact) => fact.hash));
117
+ const added: MemoryFact[] = [];
118
+ for (const item of incoming) {
119
+ const text = normalizeFactText(item.text);
120
+ if (text.length < 8 || text.length > 280 || isSecretLike(text)) continue;
121
+ const hash = factHash(text);
122
+ if (known.has(hash)) continue;
123
+ const scope: MemoryScope = item.scope === "user" ? "user" : "project";
124
+ const fact: MemoryFact = {
125
+ id: newId("mem"),
126
+ hash,
127
+ text,
128
+ scope,
129
+ createdAt: new Date().toISOString(),
130
+ ...(item.sessionId ? { sessionId: item.sessionId } : {}),
131
+ };
132
+ const path = pathForScope(cwd, scope, env);
133
+ const facts = readFactsFile(path);
134
+ facts.push(fact);
135
+ writeFactsFile(path, facts);
136
+ known.add(hash);
137
+ added.push(fact);
138
+ }
139
+ return added;
140
+ }
141
+
142
+ export function deleteFact(
143
+ cwd: string,
144
+ id: string,
145
+ env: Record<string, string | undefined> = process.env,
146
+ ): MemoryFact | undefined {
147
+ const trimmed = id.trim();
148
+ if (!trimmed) return undefined;
149
+ for (const scope of ["user", "project"] as const) {
150
+ const path = pathForScope(cwd, scope, env);
151
+ const facts = readFactsFile(path);
152
+ const index = facts.findIndex((fact) => fact.id === trimmed);
153
+ if (index < 0) continue;
154
+ const [removed] = facts.splice(index, 1);
155
+ writeFactsFile(path, facts);
156
+ return removed;
157
+ }
158
+ return undefined;
159
+ }
160
+
161
+ export function matchFact(facts: MemoryFact[], raw: string): MemoryFact | undefined {
162
+ const arg = raw.trim();
163
+ if (!arg) return undefined;
164
+ const index = Number(arg);
165
+ if (Number.isInteger(index) && index >= 1 && index <= facts.length) {
166
+ return facts[index - 1];
167
+ }
168
+ return facts.find((fact) => fact.id === arg || fact.id.endsWith(arg));
169
+ }
170
+
171
+ export function tokenizeMemoryQuery(query: string): string[] {
172
+ return query
173
+ .toLowerCase()
174
+ .split(/[^a-z0-9]+/)
175
+ .filter((token) => token.length >= 3 && !STOPWORDS.has(token));
176
+ }
177
+
178
+ export function searchFacts(
179
+ cwd: string,
180
+ query: string,
181
+ topK = 10,
182
+ env: Record<string, string | undefined> = process.env,
183
+ ): MemoryFact[] {
184
+ const facts = listFacts(cwd, env);
185
+ if (facts.length === 0) return [];
186
+ const tokens = tokenizeMemoryQuery(query);
187
+ if (tokens.length === 0) return takeRecentFacts(facts, topK);
188
+ const needle = normalizeFactText(query).toLowerCase();
189
+ const leftover = leftoverNameBoosts(facts, query, tokens);
190
+ const hits = facts
191
+ .map((fact, index) => ({
192
+ fact,
193
+ score: scoreFact(fact, index, facts.length, tokens, needle) + (leftover.get(fact.id) ?? 0),
194
+ }))
195
+ .filter((row) => row.score > 1)
196
+ .sort((a, b) => b.score - a.score)
197
+ .map((row) => row.fact);
198
+ return fillMemoryHits(hits, facts, topK);
199
+ }
200
+
201
+ function stemToken(word: string): string {
202
+ if (word.length >= 4 && word.endsWith("s") && !word.endsWith("ss")) return word.slice(0, -1);
203
+ return word;
204
+ }
205
+
206
+ function tokensOverlap(hay: string[], token: string): boolean {
207
+ const stem = stemToken(token);
208
+ return hay.some((word) => word === token || stemToken(word) === stem);
209
+ }
210
+
211
+ function isPersonalQuery(query: string): boolean {
212
+ const q = query.toLowerCase();
213
+ const asks = /\b(what'?s|whats|what is|where do|who am|which)\b/.test(q);
214
+ const self = /\b(my|i|i'm|im)\b/.test(q);
215
+ return asks && self;
216
+ }
217
+
218
+ function isCapitalized(word: string): boolean {
219
+ const first = word[0];
220
+ return Boolean(first && first === first.toUpperCase() && first !== first.toLowerCase());
221
+ }
222
+
223
+ function wordsWithCaps(text: string): string[] {
224
+ return text.split(/[^A-Za-z]+/).filter((word) => word.length >= 3);
225
+ }
226
+
227
+ function unboundNames(text: string): string[] {
228
+ const words = wordsWithCaps(text);
229
+ const bound = new Set<string>();
230
+ for (let i = 0; i < words.length - 1; i += 1) {
231
+ if (words[i]?.toLowerCase() === "in" && isCapitalized(words[i + 1] ?? "")) {
232
+ bound.add(words[i + 1] ?? "");
233
+ }
234
+ }
235
+ return words.filter((word, index) => index > 0 && isCapitalized(word) && !bound.has(word));
236
+ }
237
+
238
+ function leftoverNameBoosts(
239
+ facts: MemoryFact[],
240
+ query: string,
241
+ tokens: string[],
242
+ ): Map<string, number> {
243
+ const boosts = new Map<string, number>();
244
+ if (!isPersonalQuery(query)) return boosts;
245
+ const content = tokens.filter((token) => !QUESTION_TOKENS.has(token));
246
+ const unanswered = content.filter(
247
+ (token) => !facts.some((fact) => tokensOverlap(tokenizeMemoryQuery(fact.text), token)),
248
+ );
249
+ if (unanswered.length === 0) return boosts;
250
+ const leftovers = facts.filter(
251
+ (fact) => fact.scope === "user" && unboundNames(fact.text).length > 0,
252
+ );
253
+ if (leftovers.length !== 1) return boosts;
254
+ const only = leftovers[0];
255
+ if (only) boosts.set(only.id, 4);
256
+ return boosts;
257
+ }
258
+
259
+ function scoreFact(
260
+ fact: MemoryFact,
261
+ index: number,
262
+ total: number,
263
+ tokens: string[],
264
+ needle: string,
265
+ ): number {
266
+ const hay = fact.text.toLowerCase();
267
+ const words = tokenizeMemoryQuery(fact.text);
268
+ let score = (index + 1) / total;
269
+ if (needle && hay.includes(needle)) score += 5;
270
+ for (const token of tokens) {
271
+ if (tokensOverlap(words, token)) score += 3;
272
+ }
273
+ return score;
274
+ }
275
+
276
+ function takeRecentFacts(facts: MemoryFact[], topK: number): MemoryFact[] {
277
+ return facts.slice(-topK).reverse();
278
+ }
279
+
280
+ function fillMemoryHits(hits: MemoryFact[], all: MemoryFact[], topK: number): MemoryFact[] {
281
+ const out = hits.slice(0, topK);
282
+ const seen = new Set(out.map((fact) => fact.id));
283
+ for (const fact of all.filter((item) => item.scope === "user").reverse()) {
284
+ if (out.length >= topK) break;
285
+ if (seen.has(fact.id)) continue;
286
+ out.push(fact);
287
+ seen.add(fact.id);
288
+ }
289
+ return out.length > 0 ? out : takeRecentFacts(all, topK);
290
+ }
291
+
292
+ export function instructionsPathForFact(
293
+ cwd: string,
294
+ fact: Pick<MemoryFact, "scope">,
295
+ instructionsFile = "AGENTS.md",
296
+ env: Record<string, string | undefined> = process.env,
297
+ ): string {
298
+ return fact.scope === "user"
299
+ ? userInstructionsPath(env)
300
+ : resolve(cwd, instructionsFile.trim() || "AGENTS.md");
301
+ }
302
+
303
+ export function isFactPinned(
304
+ cwd: string,
305
+ fact: Pick<MemoryFact, "scope" | "text">,
306
+ instructionsFile = "AGENTS.md",
307
+ env: Record<string, string | undefined> = process.env,
308
+ ): boolean {
309
+ const target = instructionsPathForFact(cwd, fact, instructionsFile, env);
310
+ if (!existsSync(target)) return false;
311
+ try {
312
+ return readFileSync(target, "utf8").includes(fact.text.trim());
313
+ } catch {
314
+ return false;
315
+ }
316
+ }
317
+
318
+ export function pinFact(
319
+ cwd: string,
320
+ fact: MemoryFact,
321
+ instructionsFile = "AGENTS.md",
322
+ env: Record<string, string | undefined> = process.env,
323
+ ): { path: string } | { error: string } {
324
+ const target = instructionsPathForFact(cwd, fact, instructionsFile, env);
325
+ const line = fact.text.trim();
326
+ let current = "";
327
+ if (existsSync(target)) {
328
+ try {
329
+ current = readFileSync(target, "utf8");
330
+ } catch {
331
+ return { error: "Could not read instructions." };
332
+ }
333
+ }
334
+ if (current.includes(line)) return { path: target };
335
+ const next = current.trimEnd() ? `${current.trimEnd()}\n\n${line}\n` : `${line}\n`;
336
+ mkdirSync(resolve(target, ".."), { recursive: true });
337
+ writeFileSync(target, next);
338
+ return { path: target };
339
+ }
340
+
341
+ export function stripPinnedText(current: string, line: string): string | undefined {
342
+ const needle = line.trim();
343
+ if (!needle) return undefined;
344
+ const normalized = current.replaceAll("\r\n", "\n");
345
+ const paragraphs = normalized.split("\n\n");
346
+ const keptParas = paragraphs.filter((para) => para.trim() !== needle);
347
+ if (keptParas.length !== paragraphs.length) {
348
+ const body = keptParas.join("\n\n").trim();
349
+ return body ? `${body}\n` : "";
350
+ }
351
+ const rows = normalized.split("\n");
352
+ const keptRows = rows.filter((row) => row.trim() !== needle);
353
+ if (keptRows.length === rows.length) return undefined;
354
+ let body = keptRows.join("\n");
355
+ while (body.includes("\n\n\n")) body = body.replaceAll("\n\n\n", "\n\n");
356
+ body = body.trim();
357
+ return body ? `${body}\n` : "";
358
+ }
359
+
360
+ export function unpinFact(
361
+ cwd: string,
362
+ fact: Pick<MemoryFact, "scope" | "text">,
363
+ instructionsFile = "AGENTS.md",
364
+ env: Record<string, string | undefined> = process.env,
365
+ ): { path: string; removed: boolean } | { error: string } {
366
+ const target = instructionsPathForFact(cwd, fact, instructionsFile, env);
367
+ if (!existsSync(target)) return { path: target, removed: false };
368
+ let current: string;
369
+ try {
370
+ current = readFileSync(target, "utf8");
371
+ } catch {
372
+ return { error: "Could not read instructions." };
373
+ }
374
+ const next = stripPinnedText(current, fact.text);
375
+ if (next === undefined) return { path: target, removed: false };
376
+ try {
377
+ writeFileSync(target, next);
378
+ } catch {
379
+ return { error: "Could not write instructions." };
380
+ }
381
+ return { path: target, removed: true };
382
+ }
@@ -86,6 +86,43 @@ describe("createHarness modes", () => {
86
86
  }
87
87
  });
88
88
 
89
+ test("injects retrieved memory when the user has enabled it", async () => {
90
+ const cwd = await mkdtemp(join(tmpdir(), "harness-mem-rt-"));
91
+ const home = await mkdtemp(join(tmpdir(), "harness-mem-rt-home-"));
92
+ const prevHome = process.env.HARNESS_HOME;
93
+ process.env.HARNESS_HOME = home;
94
+ try {
95
+ const { writeMemoryPrefs } = await import("./memory/prefs.ts");
96
+ const { addFacts } = await import("./memory/store.ts");
97
+ writeMemoryPrefs({ enabled: true });
98
+ addFacts(cwd, [{ text: "Prefer bun over npm for installs", scope: "user" }]);
99
+ let prompt = "";
100
+ const harness = await createHarness({
101
+ cwd,
102
+ config: DEFAULT_CONFIG,
103
+ provider: fakeProvider,
104
+ constructAgent: (input) => {
105
+ prompt = input.systemPrompt;
106
+ return {
107
+ async run(_message, emit) {
108
+ emit({ kind: "text_delta", text: "ok" });
109
+ },
110
+ };
111
+ },
112
+ observability: noopObservability,
113
+ });
114
+ await harness.runTurn("which package manager for installs", () => undefined);
115
+ expect(prompt).toContain("## Memory");
116
+ expect(prompt).toContain("Prefer bun over npm for installs");
117
+ harness.close();
118
+ } finally {
119
+ if (prevHome === undefined) delete process.env.HARNESS_HOME;
120
+ else process.env.HARNESS_HOME = prevHome;
121
+ await rm(cwd, { recursive: true, force: true });
122
+ await rm(home, { recursive: true, force: true });
123
+ }
124
+ });
125
+
89
126
  test("accumulates usage on the runtime", async () => {
90
127
  const cwd = await mkdtemp(join(tmpdir(), "harness-spend-"));
91
128
  try {
package/src/runtime.ts CHANGED
@@ -42,6 +42,10 @@ import { type ChatFn, createOpenRouterChat } from "./evals/runner.ts";
42
42
  import { buildRemoteMcpTools } from "./integrations/remote-mcp.ts";
43
43
  import { linkedMcpSources } from "./integrations/store.ts";
44
44
  import { listUserMcpServers, userMcpToolPrefix } from "./mcp/user-servers.ts";
45
+ import { extractMemories } from "./memory/extract.ts";
46
+ import { isMemoryEnabled } from "./memory/prefs.ts";
47
+ import { formatRetrievedMemory } from "./memory/prompt.ts";
48
+ import { searchFacts } from "./memory/store.ts";
45
49
  import { createObservability } from "./observability/create.ts";
46
50
  import { noopObservability } from "./observability/noop.ts";
47
51
  import { harnessPromptRecords, syncPrompts } from "./observability/prompts.ts";
@@ -491,10 +495,11 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
491
495
  }),
492
496
  );
493
497
  }
498
+ const memoryOn = isMemoryEnabled({ configEnabled: config.memory?.enabled });
494
499
  const deps: RunTurnDeps = {
495
500
  cwd,
496
501
  name: config.name,
497
- systemPrompt,
502
+ systemPrompt: systemPromptWithMemory(systemPrompt, cwd, message, memoryOn),
498
503
  tools,
499
504
  approval,
500
505
  store,
@@ -534,6 +539,7 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
534
539
  { signal: turnOptions?.signal },
535
540
  );
536
541
  if (session) runtime.activeSessionId = session.id;
542
+ scheduleMemoryExtract(memoryOn, cwd, session, provider);
537
543
  return session;
538
544
  },
539
545
  close() {
@@ -543,3 +549,25 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
543
549
  };
544
550
  return runtime;
545
551
  }
552
+
553
+ function systemPromptWithMemory(
554
+ base: string,
555
+ cwd: string,
556
+ message: string,
557
+ enabled: boolean,
558
+ ): string {
559
+ if (!enabled) return base;
560
+ const block = formatRetrievedMemory(searchFacts(cwd, message));
561
+ if (!block) return base;
562
+ return `${base}\n\n## Memory\n${block}`;
563
+ }
564
+
565
+ function scheduleMemoryExtract(
566
+ enabled: boolean,
567
+ cwd: string,
568
+ session: Session | undefined,
569
+ provider: MainModelProvider,
570
+ ): void {
571
+ if (!enabled || !session) return;
572
+ void extractMemories({ cwd, session, provider }).catch(() => undefined);
573
+ }