diff --git a/src/functions/enrich.ts b/src/functions/enrich.ts index 4b84f666b0..e9062a6bed 100644 --- a/src/functions/enrich.ts +++ b/src/functions/enrich.ts @@ -25,11 +25,12 @@ export function registerEnrichFunction(sdk: IIIClient, kv: StateKV): void { const parts: string[] = []; const fileContextPromise = sdk - .trigger<{ sessionId: string; files: string[] }, { context: string }>({ + .trigger<{ sessionId: string; files: string[]; project?: string }, { context: string }>({ function_id: "mem::file-context", payload: { sessionId: data.sessionId, files: data.files, + ...(project !== undefined && { project }), }, }) .catch(() => ({ context: "" })); diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts index a52bf0356f..9b2bbd7283 100644 --- a/src/functions/file-index.ts +++ b/src/functions/file-index.ts @@ -6,6 +6,8 @@ import { recordAudit } from "./audit.js"; import { recordAccessBatch } from "./access-tracker.js"; import { logger } from "../logger.js"; +const SESSION_LOAD_CONCURRENCY = 4; + interface FileHistory { file: string; observations: Array<{ @@ -59,12 +61,19 @@ export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void { .slice(0, 15); const obsCache = new Map(); - for (const session of otherSessions) { - obsCache.set( - session.id, - await kv.list(KV.observations(session.id)), - ); - } + let next = 0; + const loadNext = async (): Promise => { + while (next < otherSessions.length) { + const session = otherSessions[next++]; + obsCache.set( + session.id, + await kv.list(KV.observations(session.id)), + ); + } + }; + await Promise.all( + Array.from({ length: Math.min(SESSION_LOAD_CONCURRENCY, otherSessions.length) }, loadNext), + ); for (const file of files) { const history: FileHistory = { file, observations: [] }; diff --git a/test/file-context-project.test.ts b/test/file-context-project.test.ts new file mode 100644 index 0000000000..8e94583f2f --- /dev/null +++ b/test/file-context-project.test.ts @@ -0,0 +1,143 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; + +vi.mock("../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); +vi.mock("../src/functions/access-tracker.js", () => ({ + recordAccessBatch: vi.fn(async () => {}), +})); +vi.mock("../src/functions/audit.js", () => ({ + recordAudit: vi.fn(async () => {}), +})); + +import { registerEnrichFunction } from "../src/functions/enrich.js"; +import { registerFileIndexFunction } from "../src/functions/file-index.js"; + +function mockKV(listDelayMs = 0) { + const store = new Map>(); + const stats = { inFlight: 0, maxInFlight: 0, observationLists: 0 }; + return { + stats, + get: async (scope: string, key: string): Promise => + (store.get(scope)?.get(key) as T) ?? null, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async (scope: string, key: string): Promise => { + store.get(scope)?.delete(key); + }, + list: async (scope: string): Promise => { + const isObservations = scope.startsWith("mem:obs:"); + if (isObservations) { + stats.observationLists++; + stats.inFlight++; + stats.maxInFlight = Math.max(stats.maxInFlight, stats.inFlight); + await new Promise((resolve) => setTimeout(resolve, listDelayMs)); + stats.inFlight--; + } + const entries = store.get(scope); + return entries ? (Array.from(entries.values()) as T[]) : []; + }, + }; +} + +function mockSdk() { + const functions = new Map(); + const overrides = new Map(); + return { + registerFunction: (id: string, handler: Function) => { + functions.set(id, handler); + }, + registerTrigger: () => {}, + trigger: async (input: { function_id: string; payload: unknown }) => { + const handler = overrides.get(input.function_id) ?? functions.get(input.function_id); + if (!handler) throw new Error(`No function registered: ${input.function_id}`); + return handler(input.payload); + }, + overrideTrigger: (id: string, handler: Function) => { + overrides.set(id, handler); + }, + }; +} + +async function seedSession( + kv: ReturnType, + id: string, + project: string, + startedAt: string, +) { + await kv.set("mem:sessions", id, { id, project, startedAt, status: "completed" }); + await kv.set(`mem:obs:${id}`, `obs_${id}`, { + id: `obs_${id}`, + sessionId: id, + type: "file_edit", + title: `edit in ${project}`, + narrative: `changed handler in ${project}`, + files: ["src/handler.ts"], + importance: 6, + timestamp: startedAt, + }); +} + +describe("mem::enrich and mem::file-context project scoping", () => { + let sdk: ReturnType; + + beforeEach(() => { + sdk = mockSdk(); + }); + + it("forwards the project from enrich to file-context", async () => { + const kv = mockKV(); + registerEnrichFunction(sdk as never, kv as never); + let payload: Record | undefined; + sdk.overrideTrigger("mem::file-context", async (data: Record) => { + payload = data; + return { context: "" }; + }); + sdk.overrideTrigger("mem::search", async () => ({ results: [] })); + + await sdk.trigger({ + function_id: "mem::enrich", + payload: { sessionId: "ses_now", files: ["src/handler.ts"], project: "alpha" }, + }); + + expect(payload).toMatchObject({ sessionId: "ses_now", files: ["src/handler.ts"], project: "alpha" }); + }); + + it("returns only the requested project's file history", async () => { + const kv = mockKV(); + registerEnrichFunction(sdk as never, kv as never); + registerFileIndexFunction(sdk as never, kv as never); + sdk.overrideTrigger("mem::search", async () => ({ results: [] })); + await seedSession(kv, "ses_alpha", "alpha", "2026-11-01T00:00:00.000Z"); + await seedSession(kv, "ses_beta", "beta", "2026-11-02T00:00:00.000Z"); + + const result = (await sdk.trigger({ + function_id: "mem::enrich", + payload: { sessionId: "ses_now", files: ["src/handler.ts"], project: "alpha" }, + })) as { context: string }; + + expect(result.context).toContain("edit in alpha"); + expect(result.context).not.toContain("edit in beta"); + }); + + it("loads at most 15 sessions with at most 4 lists in flight", async () => { + const kv = mockKV(5); + registerFileIndexFunction(sdk as never, kv as never); + for (let i = 0; i < 40; i++) { + await seedSession(kv, `ses_${i}`, "alpha", new Date(Date.UTC(2026, 9, 1) + i * 3600_000).toISOString()); + } + + const result = (await sdk.trigger({ + function_id: "mem::file-context", + payload: { sessionId: "ses_now", files: ["src/handler.ts"], project: "alpha" }, + })) as { context: string }; + + expect(result.context).toContain("edit in alpha"); + expect(kv.stats.observationLists).toBe(15); + expect(kv.stats.maxInFlight).toBeGreaterThan(1); + expect(kv.stats.maxInFlight).toBeLessThanOrEqual(4); + }); +});