@useavalon/caelence-agent 0.4.0 → 0.6.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.
Files changed (55) hide show
  1. package/README.md +29 -4
  2. package/desktop/src/DeskComposer.tsx +10 -0
  3. package/desktop/src/SettingsPanel.tsx +18 -0
  4. package/desktop/src/api.ts +12 -1
  5. package/desktop/src/app.css +8 -3
  6. package/desktop/src/desk-types.ts +1 -0
  7. package/desktop/src/desktop-turn.ts +7 -0
  8. package/desktop/src/stream.ts +1 -0
  9. package/desktop/src/thought.test.ts +16 -0
  10. package/desktop/src/thought.ts +15 -4
  11. package/desktop/src/turn-verbs.ts +14 -0
  12. package/desktop/src/useDeskPicker.ts +17 -1
  13. package/package.json +7 -4
  14. package/src/cli/main.test.ts +12 -0
  15. package/src/cli/main.ts +45 -5
  16. package/src/cli/slash-dispatch.test.ts +43 -0
  17. package/src/cli/slash-dispatch.ts +34 -0
  18. package/src/cli/slash.test.ts +1 -0
  19. package/src/cli/slash.ts +2 -0
  20. package/src/cli/tui-progress.ts +15 -3
  21. package/src/cli/tui.tsx +15 -1
  22. package/src/config.ts +38 -2
  23. package/src/core/events.ts +12 -9
  24. package/src/core/mode.ts +5 -0
  25. package/src/core/reasoning.test.ts +37 -0
  26. package/src/core/reasoning.ts +32 -0
  27. package/src/core/run-turn.test.ts +112 -0
  28. package/src/core/run-turn.ts +13 -1
  29. package/src/core/strands.test.ts +106 -2
  30. package/src/core/strands.ts +46 -11
  31. package/src/core/usage.test.ts +80 -1
  32. package/src/core/usage.ts +35 -3
  33. package/src/desktop/bridge.test.ts +27 -0
  34. package/src/desktop/bridge.ts +17 -5
  35. package/src/index.ts +77 -1
  36. package/src/memory/brief.ts +62 -0
  37. package/src/memory/embeddings.ts +104 -0
  38. package/src/memory/extract.ts +9 -8
  39. package/src/memory/layered.test.ts +202 -0
  40. package/src/memory/layered.ts +125 -0
  41. package/src/memory/memory-store.test.ts +299 -0
  42. package/src/memory/memory-store.ts +295 -0
  43. package/src/memory/store.ts +70 -20
  44. package/src/observability/langfuse.ts +9 -2
  45. package/src/observability/types.ts +5 -0
  46. package/src/runtime.test.ts +27 -0
  47. package/src/runtime.ts +164 -34
  48. package/src/status/categories.ts +64 -0
  49. package/src/status/default-verbs.ts +190 -0
  50. package/src/status/status-verb-categories.json +6167 -0
  51. package/src/status/status-verbs.test.ts +209 -0
  52. package/src/status/status-verbs.ts +62 -0
  53. package/src/tools/background.test.ts +304 -0
  54. package/src/tools/background.ts +432 -0
  55. package/src/tools/memory.ts +94 -0
@@ -0,0 +1,62 @@
1
+ import type { MainModelProvider } from "../core/events.ts";
2
+ import type { MemoryFact } from "./store.ts";
3
+
4
+ export const DEFAULT_BRIEF_WORDS = 180;
5
+ /** Facts handed to the model for one brief. The newest are kept when there are more. */
6
+ export const MAX_BRIEF_FACTS = 200;
7
+
8
+ /**
9
+ * The system prompt that turns a pile of remembered facts into one short brief. A brief is what
10
+ * a new chat, or a new project in the same workspace, starts from.
11
+ */
12
+ export function memoryBriefSystem(subject: string, maxWords = DEFAULT_BRIEF_WORDS): string {
13
+ return [
14
+ `Write a short brief of what is known about ${subject}, from the remembered facts below.`,
15
+ "The facts are listed oldest first. When two disagree, the later one is right; leave the earlier one out.",
16
+ "Group related points and say each thing once. Use plain sentences or short bullets.",
17
+ "Use only what the facts say. Do not add advice, guesses, or anything they do not state.",
18
+ `Stay under ${maxWords} words. Reply with the brief only, no heading and no preamble.`,
19
+ ].join(" ");
20
+ }
21
+
22
+ /**
23
+ * Consolidate facts into a brief with one model call. Returns an empty string when there are no
24
+ * facts or the model fails, so the caller keeps whatever brief it already had.
25
+ */
26
+ export async function synthesizeMemoryBrief(input: {
27
+ facts: readonly MemoryFact[];
28
+ provider: MainModelProvider;
29
+ /** What the facts are about: "this project", "the Acme workspace". */
30
+ subject: string;
31
+ maxWords?: number;
32
+ signal?: AbortSignal;
33
+ }): Promise<string> {
34
+ const facts = input.facts.slice(-MAX_BRIEF_FACTS);
35
+ if (facts.length === 0) return "";
36
+ const maxWords = input.maxWords ?? DEFAULT_BRIEF_WORDS;
37
+ let raw = "";
38
+ for await (const event of input.provider.stream(
39
+ {
40
+ system: memoryBriefSystem(input.subject, maxWords),
41
+ messages: [{ role: "user", content: facts.map((fact) => `- ${fact.text}`).join("\n") }],
42
+ maxTokens: Math.ceil(maxWords * 2.5),
43
+ },
44
+ input.signal ? { signal: input.signal } : undefined,
45
+ )) {
46
+ if (event.type === "text_delta") raw += event.text;
47
+ if (event.type === "error") return "";
48
+ }
49
+ const words = raw.trim().split(/\s+/).filter(Boolean);
50
+ // A model that ignores the limit is cut rather than trusted with the whole prompt budget.
51
+ if (words.length > maxWords * 1.5)
52
+ return `${words.slice(0, Math.floor(maxWords * 1.5)).join(" ")} …`;
53
+ return raw.trim();
54
+ }
55
+
56
+ /** The briefs as system-prompt sections, widest first so the narrower one has the last word. */
57
+ export function formatMemoryBriefs(briefs: ReadonlyArray<{ title: string; text: string }>): string {
58
+ return briefs
59
+ .filter((brief) => brief.text.trim())
60
+ .map((brief) => `### ${brief.title}\n${brief.text.trim()}`)
61
+ .join("\n\n");
62
+ }
@@ -0,0 +1,104 @@
1
+ import { OPENROUTER_DEFAULT_BASE_URL } from "../config.ts";
2
+ import { PRODUCT_NAME } from "../product.ts";
3
+
4
+ /** Turns text into vectors. One vector per input, in the same order. */
5
+ export interface Embedder {
6
+ /** Names the vector space. Vectors from two models are never compared. */
7
+ readonly model: string;
8
+ embed(texts: string[]): Promise<number[][]>;
9
+ }
10
+
11
+ export const DEFAULT_EMBEDDING_MODEL = "openai/text-embedding-3-small";
12
+
13
+ const EMBED_BATCH = 96;
14
+
15
+ /**
16
+ * An embedder for any OpenAI-compatible `/embeddings` endpoint. OpenRouter is the default.
17
+ * The texts are sent to that provider, so a host turns this on deliberately.
18
+ */
19
+ export function createOpenAICompatEmbedder(options: {
20
+ apiKey: string | (() => string);
21
+ baseUrl?: string;
22
+ model?: string;
23
+ fetch?: typeof fetch;
24
+ }): Embedder {
25
+ const baseUrl = (options.baseUrl ?? OPENROUTER_DEFAULT_BASE_URL).replace(/\/+$/, "");
26
+ const model = options.model?.trim() || DEFAULT_EMBEDDING_MODEL;
27
+ const doFetch = options.fetch ?? fetch;
28
+ const embedBatch = async (texts: string[]): Promise<number[][]> => {
29
+ const apiKey = typeof options.apiKey === "function" ? options.apiKey() : options.apiKey;
30
+ if (!apiKey.trim()) throw new Error("No API key for embeddings.");
31
+ const res = await doFetch(`${baseUrl}/embeddings`, {
32
+ method: "POST",
33
+ headers: {
34
+ Authorization: `Bearer ${apiKey}`,
35
+ "Content-Type": "application/json",
36
+ "HTTP-Referer": "https://caelence.com",
37
+ "X-Title": `${PRODUCT_NAME} memory`,
38
+ },
39
+ body: JSON.stringify({ model, input: texts }),
40
+ });
41
+ if (!res.ok) {
42
+ const body = await res.text();
43
+ throw new Error(`Embeddings ${res.status}: ${body.slice(0, 300)}`);
44
+ }
45
+ const json = (await res.json()) as {
46
+ data?: Array<{ index?: number; embedding?: unknown }>;
47
+ };
48
+ const rows = json.data ?? [];
49
+ const out: number[][] = new Array(texts.length);
50
+ rows.forEach((row, position) => {
51
+ const index = typeof row.index === "number" ? row.index : position;
52
+ if (Array.isArray(row.embedding) && index >= 0 && index < texts.length) {
53
+ out[index] = row.embedding as number[];
54
+ }
55
+ });
56
+ for (let i = 0; i < texts.length; i += 1) {
57
+ if (!Array.isArray(out[i])) throw new Error("Embeddings reply was missing a vector.");
58
+ }
59
+ return out;
60
+ };
61
+ return {
62
+ model,
63
+ async embed(texts) {
64
+ const out: number[][] = [];
65
+ for (let i = 0; i < texts.length; i += EMBED_BATCH) {
66
+ out.push(...(await embedBatch(texts.slice(i, i + EMBED_BATCH))));
67
+ }
68
+ return out;
69
+ },
70
+ };
71
+ }
72
+
73
+ export function cosineSimilarity(a: readonly number[], b: readonly number[]): number {
74
+ if (a.length === 0 || a.length !== b.length) return 0;
75
+ let dot = 0;
76
+ let normA = 0;
77
+ let normB = 0;
78
+ for (let i = 0; i < a.length; i += 1) {
79
+ const x = a[i] ?? 0;
80
+ const y = b[i] ?? 0;
81
+ dot += x * y;
82
+ normA += x * x;
83
+ normB += y * y;
84
+ }
85
+ if (normA === 0 || normB === 0) return 0;
86
+ return dot / Math.sqrt(normA * normB);
87
+ }
88
+
89
+ /**
90
+ * Merge ranked lists into one. An item's score is the sum of 1 / (k + rank) over the lists it
91
+ * appears in, so something both lists like beats something one list loves.
92
+ */
93
+ export function fuseRankings<T>(lists: T[][], keyOf: (item: T) => string, k = 60): T[] {
94
+ const scores = new Map<string, { item: T; score: number }>();
95
+ for (const list of lists) {
96
+ list.forEach((item, rank) => {
97
+ const key = keyOf(item);
98
+ const row = scores.get(key) ?? { item, score: 0 };
99
+ row.score += 1 / (k + rank + 1);
100
+ scores.set(key, row);
101
+ });
102
+ }
103
+ return [...scores.values()].sort((a, b) => b.score - a.score).map((row) => row.item);
104
+ }
@@ -1,5 +1,6 @@
1
1
  import type { MainModelProvider } from "../core/events.ts";
2
2
  import type { Session } from "../core/session.ts";
3
+ import type { MemoryStore } from "./memory-store.ts";
3
4
  import { addFacts, type MemoryScope } from "./store.ts";
4
5
 
5
6
  export const MEMORY_EXTRACT_SYSTEM = [
@@ -65,6 +66,8 @@ export async function extractMemories(input: {
65
66
  session: Session;
66
67
  provider: MainModelProvider;
67
68
  env?: Record<string, string | undefined>;
69
+ /** Where to keep the facts. Defaults to the facts files under `cwd` and the harness home. */
70
+ store?: MemoryStore;
68
71
  }): Promise<number> {
69
72
  const source = turnMemorySource(input.session);
70
73
  if (!source.trim()) return 0;
@@ -77,12 +80,10 @@ export async function extractMemories(input: {
77
80
  if (event.type === "text_delta") raw += event.text;
78
81
  if (event.type === "error") return 0;
79
82
  }
80
- return addFacts(
81
- input.cwd,
82
- parseExtractedFacts(raw).map((fact) => ({
83
- ...fact,
84
- sessionId: input.session.id,
85
- })),
86
- input.env,
87
- ).length;
83
+ const facts = parseExtractedFacts(raw).map((fact) => ({
84
+ ...fact,
85
+ sessionId: input.session.id,
86
+ }));
87
+ if (input.store) return (await input.store.add(facts)).length;
88
+ return addFacts(input.cwd, facts, input.env).length;
88
89
  }
@@ -0,0 +1,202 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { MainModelProvider, ProviderTurnRequest } from "../core/events.ts";
3
+ import { formatMemoryBriefs, memoryBriefSystem, synthesizeMemoryBrief } from "./brief.ts";
4
+ import { createLayeredMemoryStore } from "./layered.ts";
5
+ import { createInMemoryMemoryBackend, createMemoryStore } from "./memory-store.ts";
6
+
7
+ function stores() {
8
+ const project = createMemoryStore({ backend: createInMemoryMemoryBackend() });
9
+ const workspace = createMemoryStore({ backend: createInMemoryMemoryBackend() });
10
+ const layered = createLayeredMemoryStore([
11
+ { name: "project", store: project },
12
+ { name: "workspace", store: workspace },
13
+ ]);
14
+ return { project, workspace, layered };
15
+ }
16
+
17
+ describe("layered memory", () => {
18
+ test("needs a layer", () => {
19
+ expect(() => createLayeredMemoryStore([])).toThrow();
20
+ });
21
+
22
+ test("the agent's facts go to the narrowest layer only", async () => {
23
+ const { project, workspace, layered } = stores();
24
+ const added = await layered.add([{ text: "The hero uses a full-bleed photo" }]);
25
+ expect(added[0]?.layer).toBe("project");
26
+ expect(await project.list()).toHaveLength(1);
27
+ expect(await workspace.list()).toHaveLength(0);
28
+ });
29
+
30
+ test("a fact the workspace already holds is not stored again in the project", async () => {
31
+ const { project, workspace, layered } = stores();
32
+ await workspace.add([{ text: "The brand voice is plain and direct" }]);
33
+ expect(await layered.add([{ text: "the brand voice is plain and direct" }])).toHaveLength(0);
34
+ expect(await project.list()).toHaveLength(0);
35
+ });
36
+
37
+ test("search reads every layer, tags where a fact came from, and puts the narrower first", async () => {
38
+ const { workspace, layered } = stores();
39
+ await workspace.add([{ text: "Buttons use the green accent colour" }]);
40
+ await layered.add([{ text: "Buttons on this site use the orange accent colour" }]);
41
+ const hits = await layered.search("which accent colour for buttons", 2);
42
+ expect(hits.map((fact) => fact.layer)).toEqual(["project", "workspace"]);
43
+ expect(hits[0]?.text).toContain("orange");
44
+ });
45
+
46
+ test("list and listByLayer show both layers", async () => {
47
+ const { workspace, layered } = stores();
48
+ await workspace.add([{ text: "The brand voice is plain and direct" }]);
49
+ await layered.add([{ text: "The hero uses a full-bleed photo" }]);
50
+ expect((await layered.list()).map((fact) => fact.layer)).toEqual(["project", "workspace"]);
51
+ const byLayer = await layered.listByLayer();
52
+ expect(byLayer.map((row) => [row.layer, row.facts.length])).toEqual([
53
+ ["project", 1],
54
+ ["workspace", 1],
55
+ ]);
56
+ });
57
+
58
+ test("promote moves a fact to the wider layer", async () => {
59
+ const { project, workspace, layered } = stores();
60
+ const [fact] = await layered.add([{ text: "Deploys go through Cloudflare Workers" }]);
61
+ const promoted = await layered.promote(fact?.id ?? "", "workspace");
62
+ expect(promoted).toMatchObject({
63
+ layer: "workspace",
64
+ text: "Deploys go through Cloudflare Workers",
65
+ });
66
+ expect(await project.list()).toHaveLength(0);
67
+ expect((await workspace.list()).map((item) => item.text)).toEqual([
68
+ "Deploys go through Cloudflare Workers",
69
+ ]);
70
+ });
71
+
72
+ test("promote can keep the original, and joins a copy the wider layer already has", async () => {
73
+ const { project, workspace, layered } = stores();
74
+ await workspace.add([{ text: "Deploys go through Cloudflare Workers" }]);
75
+ // Written straight to the project store, as an older fact would have been.
76
+ const [fact] = await project.add([{ text: "Deploys go through Cloudflare Workers" }]);
77
+ const promoted = await layered.promote(fact?.id ?? "", "workspace", { keep: true });
78
+ expect(promoted?.layer).toBe("workspace");
79
+ expect(await workspace.list()).toHaveLength(1);
80
+ expect(await project.list()).toHaveLength(1);
81
+ });
82
+
83
+ test("promote refuses an unknown fact, an unknown layer, and a move that is not wider", async () => {
84
+ const { workspace, layered } = stores();
85
+ const [fact] = await layered.add([{ text: "The hero uses a full-bleed photo" }]);
86
+ const [wide] = await workspace.add([{ text: "The brand voice is plain and direct" }]);
87
+ expect(await layered.promote("mem_missing", "workspace")).toBeUndefined();
88
+ expect(await layered.promote(fact?.id ?? "", "galaxy")).toBeUndefined();
89
+ expect(await layered.promote(fact?.id ?? "", "project")).toBeUndefined();
90
+ expect(await layered.promote(wide?.id ?? "", "project")).toBeUndefined();
91
+ });
92
+
93
+ test("remove finds the fact in whichever layer holds it", async () => {
94
+ const { workspace, layered } = stores();
95
+ const [wide] = await workspace.add([{ text: "The brand voice is plain and direct" }]);
96
+ expect((await layered.remove(wide?.id ?? ""))?.layer).toBe("workspace");
97
+ expect(await workspace.list()).toHaveLength(0);
98
+ expect(await layered.remove("mem_missing")).toBeUndefined();
99
+ });
100
+
101
+ test("a read-only first layer stores nothing", async () => {
102
+ const project = createMemoryStore({ backend: createInMemoryMemoryBackend() });
103
+ const layered = createLayeredMemoryStore([
104
+ { name: "project", store: project, writable: false },
105
+ ]);
106
+ expect(await layered.add([{ text: "The hero uses a full-bleed photo" }])).toHaveLength(0);
107
+ });
108
+
109
+ test("a layer that fails to read does not break the others", async () => {
110
+ const { project } = stores();
111
+ await project.add([{ text: "The hero uses a full-bleed photo" }]);
112
+ const broken = {
113
+ list: async () => Promise.reject(new Error("down")),
114
+ add: async () => [],
115
+ remove: async () => undefined,
116
+ search: async () => Promise.reject(new Error("down")),
117
+ };
118
+ const layered = createLayeredMemoryStore([
119
+ { name: "project", store: project },
120
+ { name: "workspace", store: broken },
121
+ ]);
122
+ expect(await layered.search("hero photo")).toHaveLength(1);
123
+ expect(await layered.list()).toHaveLength(1);
124
+ });
125
+ });
126
+
127
+ describe("memory briefs", () => {
128
+ function provider(reply: string, seen?: ProviderTurnRequest[]): MainModelProvider {
129
+ return {
130
+ kind: "fake",
131
+ modelId: "fake",
132
+ async *stream(request) {
133
+ seen?.push(request);
134
+ yield { type: "text_delta", text: reply };
135
+ yield { type: "done" };
136
+ },
137
+ };
138
+ }
139
+ const fact = (text: string) => ({
140
+ id: `mem_${text.length}`,
141
+ hash: text,
142
+ text,
143
+ scope: "project" as const,
144
+ createdAt: new Date(0).toISOString(),
145
+ });
146
+
147
+ test("sends the facts oldest first and returns the model's brief", async () => {
148
+ const seen: ProviderTurnRequest[] = [];
149
+ const brief = await synthesizeMemoryBrief({
150
+ facts: [fact("Uses a dark palette"), fact("Deploys to Cloudflare")],
151
+ provider: provider(" Dark palette. Deploys to Cloudflare. ", seen),
152
+ subject: "this project",
153
+ });
154
+ expect(brief).toBe("Dark palette. Deploys to Cloudflare.");
155
+ expect(seen[0]?.messages[0]?.content).toBe("- Uses a dark palette\n- Deploys to Cloudflare");
156
+ expect(seen[0]?.system).toBe(memoryBriefSystem("this project"));
157
+ expect(seen[0]?.system).toContain("this project");
158
+ });
159
+
160
+ test("no facts means no model call and no brief", async () => {
161
+ const seen: ProviderTurnRequest[] = [];
162
+ expect(
163
+ await synthesizeMemoryBrief({ facts: [], provider: provider("x", seen), subject: "it" }),
164
+ ).toBe("");
165
+ expect(seen).toHaveLength(0);
166
+ });
167
+
168
+ test("a model error gives an empty brief, and an overlong one is cut", async () => {
169
+ const failing: MainModelProvider = {
170
+ kind: "fake",
171
+ modelId: "fake",
172
+ async *stream() {
173
+ yield { type: "error", message: "nope" };
174
+ },
175
+ };
176
+ expect(
177
+ await synthesizeMemoryBrief({
178
+ facts: [fact("Uses a dark palette")],
179
+ provider: failing,
180
+ subject: "it",
181
+ }),
182
+ ).toBe("");
183
+ const long = await synthesizeMemoryBrief({
184
+ facts: [fact("Uses a dark palette")],
185
+ provider: provider(Array.from({ length: 100 }, () => "word").join(" ")),
186
+ subject: "it",
187
+ maxWords: 10,
188
+ });
189
+ expect(long.split(" ")).toHaveLength(16);
190
+ expect(long.endsWith("…")).toBe(true);
191
+ });
192
+
193
+ test("formats briefs as sections and skips empty ones", () => {
194
+ expect(
195
+ formatMemoryBriefs([
196
+ { title: "Workspace", text: "Plain voice." },
197
+ { title: "Team", text: " " },
198
+ { title: "Project", text: "Dark palette." },
199
+ ]),
200
+ ).toBe("### Workspace\nPlain voice.\n\n### Project\nDark palette.");
201
+ });
202
+ });
@@ -0,0 +1,125 @@
1
+ import { fuseRankings } from "./embeddings.ts";
2
+ import type { MemoryStore, NewMemoryFact } from "./memory-store.ts";
3
+ import { factHash, type MemoryFact, normalizeFactText } from "./store.ts";
4
+
5
+ /**
6
+ * One level of shared context: a project, the team around it, the whole workspace. Each has its
7
+ * own store, so each keeps its own access rules.
8
+ */
9
+ export interface MemoryLayer {
10
+ /** Shown with every fact that comes from this layer ("project", "workspace"). */
11
+ name: string;
12
+ store: MemoryStore;
13
+ /**
14
+ * Whether `add` may write here. Facts the agent picks up go to the first writable layer. A
15
+ * wider layer is usually left read-only, so a fact only reaches it when a person promotes it.
16
+ * Defaults to true for the first layer and false for the rest.
17
+ */
18
+ writable?: boolean;
19
+ }
20
+
21
+ export interface LayeredMemoryStore extends MemoryStore {
22
+ /** Layer names, narrowest first. */
23
+ readonly layers: readonly string[];
24
+ listByLayer(): Promise<Array<{ layer: string; facts: MemoryFact[] }>>;
25
+ /**
26
+ * Move a fact to a wider layer, so everything under that layer starts with it. Returns the fact
27
+ * as it is in the target layer, or undefined when the fact or the layer is not found, or the
28
+ * target is not wider than where the fact lives. `keep` leaves the original in place.
29
+ */
30
+ promote(
31
+ id: string,
32
+ toLayer: string,
33
+ options?: { keep?: boolean },
34
+ ): Promise<MemoryFact | undefined>;
35
+ }
36
+
37
+ /**
38
+ * Several stores read as one. Layers go narrowest first (project, then team, then workspace):
39
+ * a search asks every layer and puts the narrower one first when both know something, and the
40
+ * same fact held by two layers is returned once, from the narrower.
41
+ */
42
+ export function createLayeredMemoryStore(layers: MemoryLayer[]): LayeredMemoryStore {
43
+ if (layers.length === 0) throw new Error("A layered memory store needs at least one layer.");
44
+ const writeIndex = (() => {
45
+ const marked = layers.findIndex((layer) => layer.writable === true);
46
+ if (marked >= 0) return marked;
47
+ return layers[0]?.writable === false ? -1 : 0;
48
+ })();
49
+ const tag = (fact: MemoryFact, layer: string): MemoryFact => ({ ...fact, layer });
50
+ const listLayer = async (layer: MemoryLayer): Promise<MemoryFact[]> =>
51
+ (await layer.store.list().catch(() => [])).map((fact) => tag(fact, layer.name));
52
+ const dedupe = (facts: MemoryFact[]): MemoryFact[] => {
53
+ const seen = new Set<string>();
54
+ return facts.filter((fact) => {
55
+ if (seen.has(fact.hash)) return false;
56
+ seen.add(fact.hash);
57
+ return true;
58
+ });
59
+ };
60
+
61
+ return {
62
+ layers: layers.map((layer) => layer.name),
63
+ async listByLayer() {
64
+ return Promise.all(
65
+ layers.map(async (layer) => ({ layer: layer.name, facts: await listLayer(layer) })),
66
+ );
67
+ },
68
+ async list() {
69
+ return dedupe((await Promise.all(layers.map(listLayer))).flat());
70
+ },
71
+ async add(items: NewMemoryFact[]) {
72
+ const target = layers[writeIndex];
73
+ if (!target) return [];
74
+ // What a wider layer already holds is known here too; storing it again adds nothing.
75
+ const wider = new Set<string>();
76
+ for (const layer of layers.slice(writeIndex + 1)) {
77
+ for (const fact of await layer.store.list().catch(() => [])) wider.add(fact.hash);
78
+ }
79
+ const fresh = items.filter((item) => !wider.has(factHash(normalizeFactText(item.text))));
80
+ if (fresh.length === 0) return [];
81
+ return (await target.store.add(fresh)).map((fact) => tag(fact, target.name));
82
+ },
83
+ async remove(id) {
84
+ for (const layer of layers) {
85
+ const removed = await layer.store.remove(id);
86
+ if (removed) return tag(removed, layer.name);
87
+ }
88
+ return undefined;
89
+ },
90
+ async search(query, topK = 10) {
91
+ const ranked = await Promise.all(
92
+ layers.map(async (layer) =>
93
+ (await layer.store.search(query, topK).catch(() => [])).map((fact) =>
94
+ tag(fact, layer.name),
95
+ ),
96
+ ),
97
+ );
98
+ // Fusing by hash lets a fact two layers agree on rise, and keeps the narrower copy.
99
+ return fuseRankings(ranked, (fact) => fact.hash).slice(0, topK);
100
+ },
101
+ async promote(id, toLayer, options) {
102
+ const targetIndex = layers.findIndex((layer) => layer.name === toLayer);
103
+ const target = layers[targetIndex];
104
+ if (!target) return undefined;
105
+ for (const [index, layer] of layers.entries()) {
106
+ if (index >= targetIndex) break;
107
+ const fact = (await layer.store.list()).find((item) => item.id === id);
108
+ if (!fact) continue;
109
+ const added = await target.store.add([
110
+ {
111
+ text: fact.text,
112
+ scope: fact.scope,
113
+ ...(fact.sessionId ? { sessionId: fact.sessionId } : {}),
114
+ },
115
+ ]);
116
+ const promoted =
117
+ added[0] ?? (await target.store.list()).find((item) => item.hash === fact.hash);
118
+ if (!promoted) return undefined;
119
+ if (!options?.keep) await layer.store.remove(id);
120
+ return tag(promoted, target.name);
121
+ }
122
+ return undefined;
123
+ },
124
+ };
125
+ }