@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.
@@ -74,7 +74,7 @@ export async function runTurn(
74
74
  if (!session) throw new Error("No session to edit.");
75
75
  session = await deps.store.save(replaceUserTurn(session, req.editUserTurn, req.message));
76
76
  } else {
77
- if (!session) session = await deps.store.create(deps.systemPrompt, req.model);
77
+ session ??= await deps.store.create(deps.systemPrompt, req.model);
78
78
  session = await deps.store.append(session, {
79
79
  kind: "turn",
80
80
  role: "user",
@@ -340,6 +340,68 @@ async function invokeGuarded(
340
340
  );
341
341
  }
342
342
 
343
+ async function blockedByPreTool(
344
+ def: McpToolDefinition,
345
+ input: Record<string, unknown>,
346
+ hooks?: HookRunner,
347
+ ): Promise<string | undefined> {
348
+ const hook = await hooks?.preTool(def.name, input);
349
+ if (hook && !hook.allow) {
350
+ return hook.reason ?? `Tool call "${def.name}" was blocked by a pre_tool hook.`;
351
+ }
352
+ return undefined;
353
+ }
354
+
355
+ async function approvalGranted(
356
+ def: McpToolDefinition,
357
+ approval: ApprovalGate,
358
+ callId: string,
359
+ input: Record<string, unknown>,
360
+ ): Promise<boolean> {
361
+ if (!isRiskyToolCall(def.name) && !isFileWriteTool(def.name)) return true;
362
+ return approval.request({ callId, toolName: def.name, input });
363
+ }
364
+
365
+ async function runToolHandler(
366
+ def: McpToolDefinition,
367
+ input: Record<string, unknown>,
368
+ ): Promise<{ result: ToolResult; success: boolean; errorText?: string }> {
369
+ try {
370
+ const handlerResult = await def.handler(input);
371
+ if (handlerResult.isError) {
372
+ return {
373
+ result: handlerResult,
374
+ success: false,
375
+ errorText: toolResultText(handlerResult),
376
+ };
377
+ }
378
+ return { result: handlerResult, success: true };
379
+ } catch (handlerErr) {
380
+ const errorText = errorMessage(handlerErr);
381
+ return { result: errorResult(errorText), success: false, errorText };
382
+ }
383
+ }
384
+
385
+ function isTodoItem(item: unknown): item is { id: string; content: string; status: string } {
386
+ if (!item || typeof item !== "object") return false;
387
+ const row = item as { id?: unknown; content?: unknown; status?: unknown };
388
+ return (
389
+ typeof row.id === "string" && typeof row.content === "string" && typeof row.status === "string"
390
+ );
391
+ }
392
+
393
+ function emitTodosIfNeeded(
394
+ def: McpToolDefinition,
395
+ result: ToolResult,
396
+ emit: AgentEventEmitter,
397
+ success: boolean,
398
+ ): void {
399
+ if (!success || def.name !== "todo_write") return;
400
+ const items = (result.structuredContent as { items?: unknown } | undefined)?.items;
401
+ if (!Array.isArray(items)) return;
402
+ emit({ kind: "todos", items: items.filter(isTodoItem) });
403
+ }
404
+
343
405
  async function invokeGuardedBody(
344
406
  def: McpToolDefinition,
345
407
  approval: ApprovalGate,
@@ -354,34 +416,18 @@ async function invokeGuardedBody(
354
416
 
355
417
  try {
356
418
  emit({ kind: "tool_call_start", toolName: def.name, callId, input });
357
- const hook = await hooks?.preTool(def.name, input);
358
- if (hook && !hook.allow) {
359
- errorText = hook.reason ?? `Tool call "${def.name}" was blocked by a pre_tool hook.`;
419
+ const blocked = await blockedByPreTool(def, input, hooks);
420
+ if (blocked) {
421
+ errorText = blocked;
360
422
  result = errorResult(errorText);
361
- }
362
- let approved = true;
363
- if (!result && (isRiskyToolCall(def.name) || isFileWriteTool(def.name))) {
364
- approved = await approval.request({ callId, toolName: def.name, input });
365
- }
366
- if (result) {
367
- // hook already denied
368
- } else if (!approved) {
423
+ } else if (!(await approvalGranted(def, approval, callId, input))) {
369
424
  errorText = `Tool call "${def.name}" ${REJECTED_TOOL_MESSAGE}.`;
370
425
  result = errorResult(errorText);
371
426
  } else {
372
- try {
373
- const handlerResult = await def.handler(input);
374
- if (handlerResult.isError) {
375
- errorText = toolResultText(handlerResult);
376
- result = handlerResult;
377
- } else {
378
- result = handlerResult;
379
- success = true;
380
- }
381
- } catch (handlerErr) {
382
- errorText = errorMessage(handlerErr);
383
- result = errorResult(errorText);
384
- }
427
+ const ran = await runToolHandler(def, input);
428
+ result = ran.result;
429
+ success = ran.success;
430
+ errorText = ran.errorText;
385
431
  }
386
432
  } catch (dispatchErr) {
387
433
  errorText = errorMessage(dispatchErr);
@@ -390,22 +436,7 @@ async function invokeGuardedBody(
390
436
 
391
437
  const finalResult = result ?? errorResult("tool produced no result");
392
438
  void hooks?.postTool(def.name, input, success);
393
- if (success && def.name === "todo_write") {
394
- const items = (finalResult.structuredContent as { items?: unknown } | undefined)?.items;
395
- if (Array.isArray(items)) {
396
- emit({
397
- kind: "todos",
398
- items: items.filter(
399
- (item): item is { id: string; content: string; status: string } =>
400
- !!item &&
401
- typeof item === "object" &&
402
- typeof (item as { id?: unknown }).id === "string" &&
403
- typeof (item as { content?: unknown }).content === "string" &&
404
- typeof (item as { status?: unknown }).status === "string",
405
- ),
406
- });
407
- }
408
- }
439
+ emitTodosIfNeeded(def, finalResult, emit, success);
409
440
  emit({
410
441
  kind: "tool_call_end",
411
442
  toolName: def.name,
@@ -440,6 +471,7 @@ export function buildSystemPrompt(input: {
440
471
  userInstructions?: string;
441
472
  projectInstructions?: string;
442
473
  skillCatalog?: string;
474
+ memory?: string;
443
475
  mode?: AgentMode;
444
476
  }): string {
445
477
  const parts = [
@@ -464,6 +496,7 @@ export function buildSystemPrompt(input: {
464
496
  } else if (input.instructions?.trim()) {
465
497
  parts.push("## Instructions", input.instructions.trim());
466
498
  }
499
+ if (input.memory?.trim()) parts.push("## Memory", input.memory.trim());
467
500
  if (input.skillCatalog?.trim()) parts.push(input.skillCatalog.trim());
468
501
  return parts.join("\n\n");
469
502
  }
@@ -167,6 +167,36 @@ describe("desktop bridge", () => {
167
167
  }
168
168
  });
169
169
 
170
+ test("memory is off until enabled and can store a fact", async () => {
171
+ const ctx = await withBridge();
172
+ try {
173
+ const before = await fetch(`${ctx.ready.url}/memory`, { headers: ctx.headers });
174
+ const empty = (await before.json()) as { enabled: boolean; facts: unknown[] };
175
+ expect(empty.enabled).toBe(false);
176
+ expect(empty.facts).toEqual([]);
177
+
178
+ const { addFacts } = await import("../memory/store.ts");
179
+ addFacts(ctx.cwd, [{ text: "Prefer bun over npm for installs", scope: "user" }]);
180
+ const on = await fetch(`${ctx.ready.url}/memory`, {
181
+ method: "POST",
182
+ headers: ctx.headers,
183
+ body: JSON.stringify({ enabled: true }),
184
+ });
185
+ const body = (await on.json()) as {
186
+ enabled: boolean;
187
+ facts: Array<{ text: string }>;
188
+ };
189
+ expect(body.enabled).toBe(true);
190
+ expect(body.facts.some((fact) => fact.text.includes("Prefer bun"))).toBe(true);
191
+
192
+ const settings = await fetch(`${ctx.ready.url}/settings`, { headers: ctx.headers });
193
+ const saved = (await settings.json()) as { memoryEnabled: boolean };
194
+ expect(saved.memoryEnabled).toBe(true);
195
+ } finally {
196
+ await ctx.close();
197
+ }
198
+ });
199
+
170
200
  test("slash help stays off the model", async () => {
171
201
  const ctx = await withBridge();
172
202
  try {
@@ -35,6 +35,8 @@ import {
35
35
  } from "../mcp/user-servers.ts";
36
36
  import { transcribeAudio } from "../media/openrouter-generate.ts";
37
37
  import { readMediaPrefs } from "../media/prefs.ts";
38
+ import { isMemoryEnabled, writeMemoryPrefs } from "../memory/prefs.ts";
39
+ import { deleteFact, isFactPinned, listFacts, pinFact, unpinFact } from "../memory/store.ts";
38
40
  import { PRODUCT_NAME } from "../product.ts";
39
41
  import { createHarness, type HarnessRuntime } from "../runtime.ts";
40
42
  import {
@@ -136,6 +138,20 @@ function settingsPayload(harness: HarnessRuntime) {
136
138
  googleOAuthHint: google?.clientId ? maskSecret(google.clientId) : "",
137
139
  hasMicrosoftOAuth: Boolean(microsoft?.clientId),
138
140
  microsoftOAuthHint: microsoft?.clientId ? maskSecret(microsoft.clientId) : "",
141
+ memoryEnabled: isMemoryEnabled({ configEnabled: harness.config.memory?.enabled }),
142
+ };
143
+ }
144
+
145
+ function memoryPayload(harness: HarnessRuntime) {
146
+ return {
147
+ enabled: isMemoryEnabled({ configEnabled: harness.config.memory?.enabled }),
148
+ facts: listFacts(harness.cwd).map((fact) => ({
149
+ id: fact.id,
150
+ text: fact.text,
151
+ scope: fact.scope,
152
+ createdAt: fact.createdAt,
153
+ pinned: isFactPinned(harness.cwd, fact, harness.config.instructionsFile),
154
+ })),
139
155
  };
140
156
  }
141
157
 
@@ -650,6 +666,9 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
650
666
  }
651
667
  saveProviderOAuth(body, "google");
652
668
  saveProviderOAuth(body, "microsoft");
669
+ if (typeof body.memoryEnabled === "boolean") {
670
+ writeMemoryPrefs({ enabled: body.memoryEnabled });
671
+ }
653
672
  return json({
654
673
  ok: true,
655
674
  ...settingsPayload(harness),
@@ -657,6 +676,31 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
657
676
  });
658
677
  };
659
678
 
679
+ const route_get_memory = async (_req: Request, _url: URL): Promise<Response> => {
680
+ return json(memoryPayload(harness));
681
+ };
682
+
683
+ const route_post_memory = async (req: Request, _url: URL): Promise<Response> => {
684
+ const body = await readJson(req);
685
+ if (typeof body.enabled === "boolean") {
686
+ writeMemoryPrefs({ enabled: body.enabled });
687
+ }
688
+ if (typeof body.delete === "string") {
689
+ const removed = deleteFact(harness.cwd, body.delete);
690
+ if (!removed) return json({ error: "No memory matches." }, 404);
691
+ const unpinned = unpinFact(harness.cwd, removed, harness.config.instructionsFile);
692
+ if ("error" in unpinned) return json({ error: unpinned.error }, 500);
693
+ }
694
+ if (typeof body.pin === "string") {
695
+ const fact = listFacts(harness.cwd).find((item) => item.id === body.pin);
696
+ if (!fact) return json({ error: "No memory matches." }, 404);
697
+ const pinned = pinFact(harness.cwd, fact, harness.config.instructionsFile);
698
+ if ("error" in pinned) return json({ error: pinned.error }, 500);
699
+ return json({ ok: true, path: pinned.path, ...memoryPayload(harness) });
700
+ }
701
+ return json({ ok: true, ...memoryPayload(harness) });
702
+ };
703
+
660
704
  const route_get_slash = async (_req: Request, url: URL): Promise<Response> => {
661
705
  const { filterSlashCommands } = await import("../cli/slash.ts");
662
706
  return json({ items: filterSlashCommands(url.searchParams.get("q") ?? "/") });
@@ -922,6 +966,8 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
922
966
  "POST /embed": route_post_embed,
923
967
  "GET /embed": route_get_embed,
924
968
  "POST /transcribe": route_post_transcribe,
969
+ "GET /memory": route_get_memory,
970
+ "POST /memory": route_post_memory,
925
971
  "POST /settings": route_post_settings,
926
972
  "GET /slash": route_get_slash,
927
973
  "POST /session": route_post_session,
package/src/index.ts CHANGED
@@ -79,6 +79,19 @@ export {
79
79
  runNamedEval,
80
80
  } from "./evals/runner.ts";
81
81
  export { initHost } from "./init.ts";
82
+ export { extractMemories, parseExtractedFacts } from "./memory/extract.ts";
83
+ export { isMemoryEnabled, readMemoryPrefs, writeMemoryPrefs } from "./memory/prefs.ts";
84
+ export { formatMemoryList, formatRetrievedMemory } from "./memory/prompt.ts";
85
+ export {
86
+ addFacts,
87
+ deleteFact,
88
+ listFacts,
89
+ type MemoryFact,
90
+ type MemoryScope,
91
+ pinFact,
92
+ searchFacts,
93
+ unpinFact,
94
+ } from "./memory/store.ts";
82
95
  export {
83
96
  createObservability,
84
97
  createRecordingObservability,
@@ -35,9 +35,20 @@ export interface LinkedMcpSource {
35
35
  accessToken: string;
36
36
  }
37
37
 
38
+ function trimUnderscores(value: string): string {
39
+ let trimmed = value;
40
+ while (trimmed.startsWith("_")) trimmed = trimmed.slice(1);
41
+ while (trimmed.endsWith("_")) trimmed = trimmed.slice(0, -1);
42
+ return trimmed;
43
+ }
44
+
45
+ function slugToken(value: string, pattern: RegExp): string {
46
+ return trimUnderscores(value.replace(pattern, "_"));
47
+ }
48
+
38
49
  export function namespaceRemoteTool(connectorId: string, remoteName: string): string {
39
- const prefix = connectorId.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "");
40
- const tool = remoteName.replace(/[^a-zA-Z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
50
+ const prefix = slugToken(connectorId, /[^a-zA-Z0-9]+/g);
51
+ const tool = slugToken(remoteName, /\W+/g);
41
52
  return `${prefix}__${tool}`;
42
53
  }
43
54
 
@@ -223,39 +234,58 @@ function ensureObjectSchema(schema: Record<string, unknown>): Record<string, unk
223
234
  return { type: "object", properties: {}, ...(schema as object) };
224
235
  }
225
236
 
226
- function mapCallToolResult(result: unknown): ToolResult {
227
- if (!result || typeof result !== "object") {
228
- return textResult(String(result ?? ""));
237
+ function scalarToolText(value: unknown): string | undefined {
238
+ if (value == null) return "";
239
+ if (typeof value === "string") return value;
240
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
241
+ return `${value}`;
229
242
  }
230
- const r = result as {
231
- content?: unknown;
232
- isError?: boolean;
233
- structuredContent?: Record<string, unknown>;
234
- };
235
- const isError = r.isError === true;
236
- const blocks = Array.isArray(r.content) ? r.content : [];
243
+ return undefined;
244
+ }
245
+
246
+ function contentTexts(content: unknown): string[] {
247
+ if (!Array.isArray(content)) return [];
237
248
  const textParts: string[] = [];
238
- for (const block of blocks) {
249
+ for (const block of content) {
239
250
  if (!block || typeof block !== "object") continue;
240
251
  const b = block as { type?: string; text?: string };
241
252
  if (b.type === "text" && typeof b.text === "string") textParts.push(b.text);
242
253
  else textParts.push(JSON.stringify(block));
243
254
  }
244
- if (textParts.length === 0 && r.structuredContent) {
245
- return jsonResult(r.structuredContent, isError);
246
- }
247
- if (textParts.length === 0) {
248
- return jsonResult(result as Record<string, unknown>, isError);
249
- }
250
- const text = textParts.join("\n");
255
+ return textParts;
256
+ }
257
+
258
+ function jsonObjectOrNull(text: string): Record<string, unknown> | null {
251
259
  try {
252
260
  const parsed: unknown = JSON.parse(text);
253
261
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
254
- return jsonResult(parsed, isError);
262
+ return parsed as Record<string, unknown>;
255
263
  }
256
264
  } catch {
257
265
  /* plain text */
258
266
  }
267
+ return null;
268
+ }
269
+
270
+ function mapCallToolResult(result: unknown): ToolResult {
271
+ const scalar = scalarToolText(result);
272
+ if (scalar !== undefined) return textResult(scalar);
273
+ const r = result as {
274
+ content?: unknown;
275
+ isError?: boolean;
276
+ structuredContent?: Record<string, unknown>;
277
+ };
278
+ const isError = r.isError === true;
279
+ const textParts = contentTexts(r.content);
280
+ if (textParts.length === 0 && r.structuredContent) {
281
+ return jsonResult(r.structuredContent, isError);
282
+ }
283
+ if (textParts.length === 0) {
284
+ return jsonResult(result as Record<string, unknown>, isError);
285
+ }
286
+ const text = textParts.join("\n");
287
+ const parsed = jsonObjectOrNull(text);
288
+ if (parsed) return jsonResult(parsed, isError);
259
289
  return textResult(text, isError);
260
290
  }
261
291
 
@@ -0,0 +1,81 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { MainModelProvider } from "../core/events.ts";
6
+ import { createMemorySessionStore } from "../core/session.ts";
7
+ import { extractMemories, parseExtractedFacts, turnMemorySource } from "./extract.ts";
8
+ import { listFacts } from "./store.ts";
9
+
10
+ describe("memory extract", () => {
11
+ test("parses a JSON array and ignores chatter", () => {
12
+ expect(
13
+ parseExtractedFacts(
14
+ 'Here you go:\n[{"text":"Prefer bun","scope":"user"},{"text":"Bridge is loopback","scope":"project"}]\n',
15
+ ),
16
+ ).toEqual([
17
+ { text: "Prefer bun", scope: "user" },
18
+ { text: "Bridge is loopback", scope: "project" },
19
+ ]);
20
+ expect(parseExtractedFacts("nothing durable")).toEqual([]);
21
+ expect(parseExtractedFacts("[]")).toEqual([]);
22
+ });
23
+
24
+ test("builds a source from the last user, assistant, and tools", async () => {
25
+ const store = createMemorySessionStore();
26
+ let session = await store.create("sys");
27
+ session = await store.append(session, { kind: "turn", role: "user", content: "use bun" });
28
+ session = await store.append(session, {
29
+ kind: "tool",
30
+ name: "read_file",
31
+ callId: "c1",
32
+ status: "ok",
33
+ preview: "package.json",
34
+ });
35
+ session = await store.append(session, {
36
+ kind: "turn",
37
+ role: "assistant",
38
+ content: "I will keep using bun.",
39
+ });
40
+ const source = turnMemorySource(session);
41
+ expect(source).toContain("use bun");
42
+ expect(source).toContain("I will keep using bun.");
43
+ expect(source).toContain("read_file: package.json");
44
+ });
45
+
46
+ test("stores extracted facts from the provider", async () => {
47
+ const cwd = await mkdtemp(join(tmpdir(), "harness-mem-ex-"));
48
+ const home = await mkdtemp(join(tmpdir(), "harness-mem-ex-home-"));
49
+ const env = { HARNESS_HOME: home };
50
+ const provider: MainModelProvider = {
51
+ kind: "fake",
52
+ modelId: "fake",
53
+ async *stream() {
54
+ yield {
55
+ type: "text_delta",
56
+ text: '[{"text":"Prefer bun over npm for installs","scope":"user"}]',
57
+ };
58
+ yield { type: "done" };
59
+ },
60
+ };
61
+ try {
62
+ const store = createMemorySessionStore();
63
+ let session = await store.create("sys");
64
+ session = await store.append(session, {
65
+ kind: "turn",
66
+ role: "user",
67
+ content: "always use bun",
68
+ });
69
+ session = await store.append(session, {
70
+ kind: "turn",
71
+ role: "assistant",
72
+ content: "I will use bun.",
73
+ });
74
+ expect(await extractMemories({ cwd, session, provider, env })).toBe(1);
75
+ expect(listFacts(cwd, env)[0]?.text).toContain("Prefer bun");
76
+ } finally {
77
+ await rm(cwd, { recursive: true, force: true });
78
+ await rm(home, { recursive: true, force: true });
79
+ }
80
+ });
81
+ });
@@ -0,0 +1,88 @@
1
+ import type { MainModelProvider } from "../core/events.ts";
2
+ import type { Session } from "../core/session.ts";
3
+ import { addFacts, type MemoryScope } from "./store.ts";
4
+
5
+ export const MEMORY_EXTRACT_SYSTEM = [
6
+ "Extract durable facts worth remembering in later chats with this coding agent.",
7
+ "Keep: user preferences, stack and tool choices, project decisions, stable conventions.",
8
+ "Write each pref as a short factual sentence the user might ask about later.",
9
+ "Drop: secrets, keys, one-off task details, file contents, compliments, transient errors, anything already obvious from the repo.",
10
+ 'Reply with a JSON array only. Each item is {"text":"short sentence","scope":"user"|"project"}.',
11
+ "scope is user for personal style or prefs, project for this repository.",
12
+ "If nothing is durable, reply [].",
13
+ ].join(" ");
14
+
15
+ export interface ExtractedFact {
16
+ text: string;
17
+ scope: MemoryScope;
18
+ }
19
+
20
+ export function parseExtractedFacts(raw: string): ExtractedFact[] {
21
+ const text = raw.trim();
22
+ if (!text) return [];
23
+ const start = text.indexOf("[");
24
+ const end = text.lastIndexOf("]");
25
+ if (start < 0 || end <= start) return [];
26
+ try {
27
+ const parsed = JSON.parse(text.slice(start, end + 1)) as unknown;
28
+ if (!Array.isArray(parsed)) return [];
29
+ const out: ExtractedFact[] = [];
30
+ for (const item of parsed) {
31
+ if (!item || typeof item !== "object") continue;
32
+ const row = item as { text?: unknown; scope?: unknown };
33
+ if (typeof row.text !== "string") continue;
34
+ out.push({
35
+ text: row.text,
36
+ scope: row.scope === "user" ? "user" : "project",
37
+ });
38
+ }
39
+ return out;
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+
45
+ export function turnMemorySource(session: Session): string {
46
+ let user = "";
47
+ let assistant = "";
48
+ const tools: string[] = [];
49
+ for (const message of session.messages) {
50
+ if (message.kind === "turn" && message.role === "user") user = message.content;
51
+ if (message.kind === "turn" && message.role === "assistant") assistant = message.content;
52
+ if (message.kind === "tool" && message.status === "ok" && message.preview) {
53
+ tools.push(`${message.name}: ${message.preview}`);
54
+ }
55
+ }
56
+ if (!user.trim() && !assistant.trim()) return "";
57
+ const clip = (value: string) => (value.length > 4000 ? `${value.slice(0, 4000)}\n…` : value);
58
+ const parts = [`User:\n${clip(user)}`, `Assistant:\n${clip(assistant)}`];
59
+ if (tools.length > 0) parts.push(`Tools:\n${clip(tools.slice(-6).join("\n"))}`);
60
+ return parts.join("\n\n");
61
+ }
62
+
63
+ export async function extractMemories(input: {
64
+ cwd: string;
65
+ session: Session;
66
+ provider: MainModelProvider;
67
+ env?: Record<string, string | undefined>;
68
+ }): Promise<number> {
69
+ const source = turnMemorySource(input.session);
70
+ if (!source.trim()) return 0;
71
+ let raw = "";
72
+ for await (const event of input.provider.stream({
73
+ system: MEMORY_EXTRACT_SYSTEM,
74
+ messages: [{ role: "user", content: source }],
75
+ maxTokens: 300,
76
+ })) {
77
+ if (event.type === "text_delta") raw += event.text;
78
+ if (event.type === "error") return 0;
79
+ }
80
+ return addFacts(
81
+ input.cwd,
82
+ parseExtractedFacts(raw).map((fact) => ({
83
+ ...fact,
84
+ sessionId: input.session.id,
85
+ })),
86
+ input.env,
87
+ ).length;
88
+ }
@@ -0,0 +1,53 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { isMemoryEnabled, writeMemoryPrefs } from "./prefs.ts";
6
+ import { formatMemoryList, formatRetrievedMemory } from "./prompt.ts";
7
+
8
+ describe("memory prefs", () => {
9
+ test("is off unless the user or config turns it on", async () => {
10
+ const home = await mkdtemp(join(tmpdir(), "harness-mem-pref-"));
11
+ const env = { HARNESS_HOME: home };
12
+ try {
13
+ expect(isMemoryEnabled({ env })).toBe(false);
14
+ expect(isMemoryEnabled({ configEnabled: true, env })).toBe(true);
15
+ writeMemoryPrefs({ enabled: false }, env);
16
+ expect(isMemoryEnabled({ configEnabled: true, env })).toBe(false);
17
+ writeMemoryPrefs({ enabled: true }, env);
18
+ expect(isMemoryEnabled({ env })).toBe(true);
19
+ } finally {
20
+ await rm(home, { recursive: true, force: true });
21
+ }
22
+ });
23
+
24
+ test("formats a retrieved block and a slash list", () => {
25
+ expect(formatRetrievedMemory([])).toBe("");
26
+ const retrieved = formatRetrievedMemory([
27
+ {
28
+ id: "mem_1",
29
+ hash: "a",
30
+ text: "Prefer bun",
31
+ scope: "user",
32
+ createdAt: "2026-01-01T00:00:00.000Z",
33
+ },
34
+ ]);
35
+ expect(retrieved).toContain("stored prefs");
36
+ expect(retrieved).toContain("- Prefer bun");
37
+ expect(formatMemoryList({ enabled: false, facts: [] })).toContain("Memory is off");
38
+ expect(
39
+ formatMemoryList({
40
+ enabled: true,
41
+ facts: [
42
+ {
43
+ id: "mem_1",
44
+ hash: "a",
45
+ text: "Prefer bun",
46
+ scope: "user",
47
+ createdAt: "2026-01-01T00:00:00.000Z",
48
+ },
49
+ ],
50
+ }),
51
+ ).toContain("1 user Prefer bun");
52
+ });
53
+ });
@@ -0,0 +1,47 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { harnessHome } from "../desktop/secrets.ts";
4
+
5
+ export interface MemoryPrefs {
6
+ enabled: boolean;
7
+ }
8
+
9
+ export function memoryPrefsPath(env: Record<string, string | undefined> = process.env): string {
10
+ return resolve(harnessHome(env), "memory.json");
11
+ }
12
+
13
+ export function readMemoryPrefs(
14
+ env: Record<string, string | undefined> = process.env,
15
+ ): Partial<MemoryPrefs> {
16
+ const path = memoryPrefsPath(env);
17
+ if (!existsSync(path)) return {};
18
+ try {
19
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<MemoryPrefs>;
20
+ if (typeof parsed.enabled === "boolean") return { enabled: parsed.enabled };
21
+ return {};
22
+ } catch {
23
+ return {};
24
+ }
25
+ }
26
+
27
+ export function writeMemoryPrefs(
28
+ patch: Partial<MemoryPrefs>,
29
+ env: Record<string, string | undefined> = process.env,
30
+ ): MemoryPrefs {
31
+ const next: MemoryPrefs = {
32
+ enabled: patch.enabled ?? readMemoryPrefs(env).enabled ?? false,
33
+ };
34
+ const path = memoryPrefsPath(env);
35
+ mkdirSync(resolve(path, ".."), { recursive: true });
36
+ writeFileSync(path, `${JSON.stringify(next, null, "\t")}\n`);
37
+ return next;
38
+ }
39
+
40
+ export function isMemoryEnabled(input: {
41
+ configEnabled?: boolean;
42
+ env?: Record<string, string | undefined>;
43
+ }): boolean {
44
+ const prefs = readMemoryPrefs(input.env);
45
+ if (typeof prefs.enabled === "boolean") return prefs.enabled;
46
+ return input.configEnabled === true;
47
+ }