diff --git a/apps/server/package.json b/apps/server/package.json index 487a10083332a..cb5a586d91543 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -32,6 +32,7 @@ "record:fx-replay": "node scripts/record-fx-acp-replay-fixture.ts", "record:kiro-replay": "node scripts/record-kiro-acp-replay-fixture.ts", "record:muse-replay": "node scripts/record-muse-msp-replay-fixture.ts", + "replay:project-memory": "node --experimental-strip-types scripts/replay-project-memory.ts", "generate": "graphqlgen", "generate:expo-schema": "node scripts/fetch-expo-schema.ts" }, diff --git a/apps/server/scripts/replay-project-memory.test.ts b/apps/server/scripts/replay-project-memory.test.ts new file mode 100644 index 0000000000000..b0a7cc1ff26ae --- /dev/null +++ b/apps/server/scripts/replay-project-memory.test.ts @@ -0,0 +1,191 @@ +// @effect-diagnostics processEnvInEffect:off - the guard reads HOME and T3CODE_HOME, and this test points both at a temp directory +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as NodeOS from "node:os"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +import { replayProjectMemory, type ReplayRow } from "./replay-project-memory.ts"; + +const facts = [ + { + id: "fact-one", + project_id: "replay-project", + content: "Cache keys include tenant IDs.", + entities_json: ["cache", "tenant"], + tags_json: ["isolation"], + origin_thread: "other-thread", + trust: 0.5, + created_at: "2026-11-02T03:39:00.936Z", + }, +]; + +const messages = [ + { + message_id: "match", + project_id: "replay-project", + thread_id: "asking-thread", + payload_json: JSON.stringify({ + text: "Change cache keys to include tenant IDs.", + createdBy: "user", + }), + }, + { + message_id: "greeting", + project_id: "replay-project", + thread_id: "asking-thread", + text: "hello there", + created_by: "agent", + }, + { + message_id: "unrelated", + project_id: "replay-project", + thread_id: "asking-thread", + text: "garden bicycle banana weather holiday", + created_by: "user", + }, + { + message_id: "slash", + project_id: "replay-project", + thread_id: "asking-thread", + text: "/compact the tenant cache", + created_by: "user", + }, +]; + +it.effect("replays invented facts through recall and names the gate", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-memory-replay-test-" }); + const factsPath = path.join(directory, "facts.json"); + const messagesPath = path.join(directory, "msgs.json"); + const out = path.join(directory, "out"); + yield* fs.writeFileString(factsPath, JSON.stringify(facts)); + yield* fs.writeFileString(messagesPath, JSON.stringify(messages)); + const { rows, summary } = yield* replayProjectMemory({ + facts: factsPath, + messages: messagesPath, + out, + }); + const byId = new Map(rows.map((row) => [row.messageId, row])); + const match = byId.get("match"); + assert.equal(match?.gate, "delivered"); + assert.deepEqual(match?.deliveredFactIds, ["fact-one"]); + assert.equal(match?.createdBy, "user"); + assert.equal(match?.characters, "Change cache keys to include tenant IDs.".length); + assert.isAbove(match?.candidatesMs ?? -1, -1); + assert.equal(typeof match?.candidatesMs, "number"); + assert.equal(byId.get("greeting")?.gate, "not_substantive"); + assert.equal(byId.get("greeting")?.candidatesMs, null); + assert.deepEqual(byId.get("greeting")?.deliveredFactIds, []); + assert.equal(byId.get("unrelated")?.gate, "no_match"); + assert.deepEqual(byId.get("unrelated")?.deliveredFactIds, []); + assert.equal(byId.get("slash")?.gate, "slash"); + assert.equal(summary.byGate.delivered, 1); + assert.equal(summary.byGate.not_substantive, 1); + assert.equal(summary.byGate.no_match, 1); + assert.equal(summary.byGate.slash, 1); + assert.equal(summary.byCreatedBy.user?.messages, 3); + assert.equal(summary.byCreatedBy.agent?.messages, 1); + assert.equal(summary.lookupLatencyMs.n, 2); + assert.equal(summary.factsLoaded, 1); + const written = ( + JSON.parse(yield* fs.readFileString(path.join(out, "summary.json"))) as { + messages: number; + } + ).messages; + assert.equal(written, 4); + const lines = (yield* fs.readFileString(path.join(out, "results.ndjson"))) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as ReplayRow); + assert.equal(lines.length, 4); + yield* fs.writeFileString(factsPath, "[]"); + const failure = yield* replayProjectMemory({ + facts: factsPath, + messages: messagesPath, + out, + factCount: 1, + }).pipe( + Effect.as("unexpected success"), + Effect.catchCause((cause) => Effect.succeed(Cause.pretty(cause))), + ); + assert.include(failure, "Cannot scale an empty fact corpus"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("refuses a case-variant path and a symlink into the stand-in state directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-memory-replay-guard-" }); + const home = path.join(directory, "home"); + const state = path.join(home, ".t3", "userdata"); + yield* fs.makeDirectory(state, { recursive: true }); + const inputs = path.join(directory, "inputs"); + yield* fs.makeDirectory(inputs); + const factsPath = path.join(inputs, "facts.json"); + const messagesPath = path.join(inputs, "msgs.json"); + yield* fs.writeFileString(factsPath, JSON.stringify(facts)); + yield* fs.writeFileString(messagesPath, JSON.stringify(messages)); + const link = path.join(directory, "state-link"); + yield* fs.symlink(state, link); + const previousHome = process.env.HOME; + const previousState = process.env.T3CODE_HOME; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (previousHome === undefined) delete process.env.HOME; + else process.env.HOME = previousHome; + if (previousState === undefined) delete process.env.T3CODE_HOME; + else process.env.T3CODE_HOME = previousState; + }), + ); + process.env.HOME = home; + process.env.T3CODE_HOME = home; + assert.equal(NodeOS.homedir(), home); + + const refusal = (out: string) => + replayProjectMemory({ facts: factsPath, messages: messagesPath, out }).pipe( + Effect.exit, + Effect.map((exit) => (Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "")), + ); + const linkedOut = path.join(link, "out"); + assert.include(yield* refusal(linkedOut), "Refusing to touch live T3 data"); + assert.isFalse(yield* fs.exists(path.join(linkedOut, "results.ndjson"))); + + const foldedOut = path.join(home, ".T3", "UserData", "out"); + const identity = (file: string) => + fs.stat(file).pipe( + Effect.map((info) => (Option.isSome(info.ino) ? `${info.dev}:${info.ino.value}` : null)), + Effect.orElseSucceed(() => null), + ); + const stateId = yield* identity(state); + const foldedId = yield* identity(path.dirname(foldedOut)); + if (stateId !== null && foldedId === stateId) { + assert.include(yield* refusal(foldedOut), "Refusing to touch live T3 data"); + assert.isFalse(yield* fs.exists(path.join(state, "out", "results.ndjson"))); + } else { + const distinct = yield* replayProjectMemory({ + facts: factsPath, + messages: messagesPath, + out: foldedOut, + }).pipe(Effect.exit); + const message = Exit.isFailure(distinct) ? Cause.pretty(distinct.cause) : ""; + assert.notInclude(message, "Refusing to touch live T3 data"); + } + + const allowed = yield* replayProjectMemory({ + facts: factsPath, + messages: messagesPath, + out: path.join(directory, "allowed"), + }); + assert.equal(allowed.summary.factsLoaded, 1); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); diff --git a/apps/server/scripts/replay-project-memory.ts b/apps/server/scripts/replay-project-memory.ts new file mode 100644 index 0000000000000..007e217acd95b --- /dev/null +++ b/apps/server/scripts/replay-project-memory.ts @@ -0,0 +1,749 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + CommandId, + EnvironmentId, + EventId, + MessageId, + ProjectFactId, + ProjectId, + ProviderInstanceId, + RunId, + ThreadId, + type ApplicationProjectEvent, + type OrchestrationV2DomainEvent, +} from "@t3tools/contracts"; +// @effect-diagnostics nodeBuiltinImport:off - realpath plus inode identity is how a case variant or a symlink is the same directory +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodeURL from "node:url"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Tracer from "effect/Tracer"; + +import * as ServerEnvironment from "../src/environment/ServerEnvironment.ts"; +import * as ProjectStore from "../src/orchestration-v2/ProjectStore.ts"; +import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts"; +import * as ThreadSearch from "../src/orchestration-v2/ThreadSearch.ts"; +import * as SqlitePersistence from "../src/persistence/Sqlite.ts"; +import * as HolographicMemory from "../src/project/knowledge/HolographicMemory.ts"; +import * as ProjectKnowledge from "../src/project/knowledge/ProjectKnowledge.ts"; + +const KNOWLEDGE_ALLOWANCE = 48_000; +const RECALL_TIMEOUT = "1 second"; +const GATES = [ + "hand_picked", + "slash", + "not_substantive", + "allowance", + "kernel_unavailable", + "no_match", + "resolve_failed", + "delivered", + "failed", + "timeout", +] as const; + +const environmentId = EnvironmentId.make("project-memory-replay"); +const providerInstanceId = ProviderInstanceId.make("replay"); +const at = DateTime.makeUnsafe(Date.UTC(2026, 10, 16)); + +export interface ReplayOptions { + readonly facts: string; + readonly messages: string; + readonly out: string; + readonly project?: string; + readonly factCount?: number; + readonly limit?: number; +} + +interface NormalizedFact { + readonly id: string; + readonly projectId: string; + readonly content: string; + readonly entities: ReadonlyArray; + readonly tags: ReadonlyArray; + readonly originThread: string | null; + readonly trust: number | null; + readonly createdAt: string | null; +} + +interface NormalizedMessage { + readonly messageId: string; + readonly projectId: string; + readonly threadId: string; + readonly createdBy: string; + readonly text: string; +} + +export interface ReplayRow { + readonly messageId: string; + readonly projectId: string; + readonly threadId: string; + readonly createdBy: string; + readonly characters: number; + readonly gate: string; + readonly deliveredFactIds: ReadonlyArray; + readonly wallMs: number; + readonly candidatesMs: number | null; + readonly scoringMs: number | null; + readonly resolveMs: number | null; + readonly seenMs: number | null; +} + +interface Distribution { + readonly n: number; + readonly p50: number | null; + readonly p90: number | null; + readonly p99: number | null; + readonly max: number | null; +} + +const directoryIdentity = (file: string) => { + try { + const stat = NodeFS.statSync(file); + return { dev: stat.dev, ino: stat.ino }; + } catch { + return null; + } +}; + +const nearestExisting = (path: Path.Path, file: string) => { + let current = path.resolve(file); + while (directoryIdentity(current) === null) { + const parent = path.dirname(current); + if (parent === current) break; + current = parent; + } + return NodeFS.realpathSync(current); +}; + +const resolvesInside = (path: Path.Path, file: string, root: string) => { + const rootIdentity = directoryIdentity(root); + if (rootIdentity === null) return false; + let current = nearestExisting(path, file); + while (true) { + const identity = directoryIdentity(current); + if (identity !== null && identity.dev === rootIdentity.dev && identity.ino === rootIdentity.ino) + return true; + const parent = path.dirname(current); + if (parent === current) return false; + current = parent; + } +}; + +const assertReplayPath = (path: Path.Path, file: string) => { + const roots = [path.join(NodeOS.homedir(), ".t3", "userdata")]; + if (process.env.T3CODE_HOME) + roots.push(path.join(path.resolve(process.env.T3CODE_HOME), "userdata")); + for (const root of roots) { + if (resolvesInside(path, file, root)) + throw new Error(`Refusing to touch live T3 data at ${path.resolve(file)}`); + } +}; + +const parseJsonArray = (text: string): unknown[] => { + const parsed: unknown = JSON.parse(text); + if (!Array.isArray(parsed)) throw new Error("expected a JSON array"); + return parsed; +}; + +const encodeJson = (value: unknown) => JSON.stringify(value); +const encodePretty = (value: unknown) => JSON.stringify(value, null, 2); + +const positiveInteger = (name: string, value: string | undefined): number | undefined => { + if (value === undefined) return undefined; + const parsed = Number(value); + if (!Number.isInteger(parsed) || parsed < 1) + throw new Error(`${name} must be a positive integer`); + return parsed; +}; + +export const parseReplayArgs = (argv: ReadonlyArray): ReplayOptions => { + const read = (name: string) => { + const index = argv.indexOf(name); + if (index < 0) return undefined; + const value = argv[index + 1]; + if (value === undefined || value.startsWith("--")) throw new Error(`${name} needs a value`); + return value; + }; + const factsPath = read("--facts"); + const messagesPath = read("--messages"); + const out = read("--out"); + if (!factsPath || !messagesPath || !out) + throw new Error( + "Usage: replay-project-memory.ts --facts --messages --out [--project ] [--fact-count ] [--limit ]", + ); + const project = read("--project"); + const factCount = positiveInteger("--fact-count", read("--fact-count")); + const limit = positiveInteger("--limit", read("--limit")); + return { + facts: factsPath, + messages: messagesPath, + out, + ...(project ? { project } : {}), + ...(factCount === undefined ? {} : { factCount }), + ...(limit === undefined ? {} : { limit }), + }; +}; + +const labels = (value: unknown, field: string): ReadonlyArray => { + const parsed = typeof value === "string" ? JSON.parse(value) : value; + if (!Array.isArray(parsed)) throw new Error(`${field} must be a JSON array`); + return parsed + .filter((item): item is string => typeof item === "string") + .map((item) => item.trim()) + .filter((item) => item !== "") + .map((item) => item.slice(0, 200)) + .slice(0, 32); +}; + +const asRecord = (value: unknown, label: string): Record => { + if (typeof value !== "object" || value === null) throw new Error(`${label} must be an object`); + return value as Record; +}; + +const normalizeFact = (value: unknown): NormalizedFact => { + const row = asRecord(value, "fact"); + const content = typeof row.content === "string" ? row.content.trim() : ""; + if (typeof row.id !== "string" || row.id.trim() === "") throw new Error("fact id is missing"); + if (typeof row.project_id !== "string" || row.project_id.trim() === "") + throw new Error(`fact ${row.id} has no project_id`); + if (content === "" || content.length > 12_000) + throw new Error(`fact ${row.id} content is empty or longer than 12000 characters`); + const trust = row.trust === undefined || row.trust === null ? null : Number(row.trust); + if (trust !== null && (!Number.isFinite(trust) || trust < 0 || trust > 1)) + throw new Error(`fact ${row.id} trust is not between 0 and 1`); + const createdAt = typeof row.created_at === "string" ? row.created_at : null; + const origin = + typeof row.origin_thread === "string" && row.origin_thread.trim() !== "" + ? row.origin_thread + : null; + return { + id: row.id, + projectId: row.project_id, + content, + entities: labels(row.entities_json ?? "[]", `${row.id} entities_json`), + tags: labels(row.tags_json ?? "[]", `${row.id} tags_json`), + originThread: origin, + trust, + createdAt, + }; +}; + +const messageText = (row: Record): { text: string; createdBy: string } => { + if (typeof row.text === "string") { + const createdBy = + typeof row.created_by === "string" + ? row.created_by + : typeof row.createdBy === "string" + ? row.createdBy + : "unknown"; + return { text: row.text, createdBy }; + } + const payload = + typeof row.payload_json === "string" ? JSON.parse(row.payload_json) : row.payload_json; + const body = asRecord(payload, "payload_json"); + return { + text: typeof body.text === "string" ? body.text : "", + createdBy: typeof body.createdBy === "string" ? body.createdBy : "unknown", + }; +}; + +const normalizeMessage = (value: unknown): NormalizedMessage => { + const row = asRecord(value, "message"); + if (typeof row.message_id !== "string" || row.message_id.trim() === "") + throw new Error("message_id is missing"); + if (typeof row.project_id !== "string" || typeof row.thread_id !== "string") + throw new Error(`message ${row.message_id} is missing project_id or thread_id`); + const { text, createdBy } = messageText(row); + return { + messageId: row.message_id, + projectId: row.project_id, + threadId: row.thread_id, + createdBy, + text, + }; +}; + +const scaleFacts = ( + facts: ReadonlyArray, + count: number, +): ReadonlyArray => { + const sorted = [...facts].sort((left, right) => + left.id < right.id ? -1 : left.id > right.id ? 1 : 0, + ); + if (count <= sorted.length) return sorted.slice(0, count); + if (sorted.length === 0) throw new Error("Cannot scale an empty fact corpus"); + const scaled = [...sorted]; + let copy = 1; + while (scaled.length < count) { + for (const fact of sorted) { + if (scaled.length >= count) break; + scaled.push({ ...fact, id: `replay-copy:${copy}:${fact.id}` }); + } + copy += 1; + } + return scaled; +}; + +const selectCorpus = ( + facts: ReadonlyArray, + messages: ReadonlyArray, + options: ReplayOptions, +): { + readonly facts: ReadonlyArray; + readonly messages: ReadonlyArray; + readonly project: string | null; + readonly factScale: "as-exported" | "sample" | "duplicate"; +} => { + const project = + options.project ?? + (options.factCount === undefined + ? null + : ([ + ...facts.reduce( + (counts, fact) => counts.set(fact.projectId, (counts.get(fact.projectId) ?? 0) + 1), + new Map(), + ), + ].sort((left, right) => right[1] - left[1] || (left[0] < right[0] ? -1 : 1))[0]?.[0] ?? + null)); + const inProject = project === null ? facts : facts.filter((fact) => fact.projectId === project); + if (project !== null && inProject.length === 0) + throw new Error(`No facts for project ${project}`); + const scaled = + options.factCount === undefined ? inProject : scaleFacts(inProject, options.factCount); + const factScale = + options.factCount === undefined + ? "as-exported" + : options.factCount < inProject.length + ? "sample" + : options.factCount > inProject.length + ? "duplicate" + : "as-exported"; + const projectMessages = + project === null ? messages : messages.filter((message) => message.projectId === project); + const limited = + options.limit === undefined ? projectMessages : projectMessages.slice(0, options.limit); + return { facts: scaled, messages: limited, project, factScale }; +}; + +const distribution = (values: ReadonlyArray): Distribution => { + const sorted = [...values].sort((left, right) => left - right); + const at = (percentile: number) => + sorted.length === 0 + ? null + : sorted[ + Math.min( + sorted.length - 1, + Math.max(0, Math.ceil((percentile / 100) * sorted.length) - 1), + ) + ]!; + return { n: sorted.length, p50: at(50), p90: at(90), p99: at(99), max: sorted.at(-1) ?? null }; +}; + +const exceeded = (values: ReadonlyArray) => ({ + "150": values.filter((ms) => ms > 150).length, + "300": values.filter((ms) => ms > 300).length, + "500": values.filter((ms) => ms > 500).length, + "1000": values.filter((ms) => ms > 1000).length, +}); + +const emptyGates = (): Record => Object.fromEntries(GATES.map((gate) => [gate, 0])); + +export const summarizeReplay = ( + rows: ReadonlyArray, + meta: { + readonly factsLoaded: number; + readonly factScale: "as-exported" | "sample" | "duplicate"; + readonly project: string | null; + readonly knowledgeAllowance: number; + readonly recallTimeout: string; + readonly citation: string; + readonly warmupExcluded: number; + }, +) => { + const byGate = emptyGates(); + const byCreatedBy: Record }> = {}; + for (const row of rows) { + byGate[row.gate] = (byGate[row.gate] ?? 0) + 1; + const bucket = byCreatedBy[row.createdBy] ?? { messages: 0, byGate: {} }; + bucket.messages += 1; + bucket.byGate[row.gate] = (bucket.byGate[row.gate] ?? 0) + 1; + byCreatedBy[row.createdBy] = bucket; + } + const lookup = rows.filter((row) => row.candidatesMs !== null); + const stage = (pick: (row: ReplayRow) => number | null) => + distribution( + lookup.flatMap((row) => { + const value = pick(row); + return value === null ? [] : [value]; + }), + ); + const walls = rows.map((row) => row.wallMs); + const lookupWalls = lookup.map((row) => row.wallMs); + return { + ...meta, + messages: rows.length, + percentile: "nearest-rank ceil(p/100*n)-1", + byGate, + byCreatedBy, + latencyMs: distribution(walls), + lookupLatencyMs: distribution(lookupWalls), + exceededMs: { all: exceeded(walls), lookup: exceeded(lookupWalls) }, + stageMs: { + candidates: stage((row) => row.candidatesMs), + scoring: stage((row) => row.scoringMs), + resolve: stage((row) => row.resolveMs), + seen: stage((row) => row.seenMs), + }, + }; +}; + +const knowledgeLayer = (dbPath: string) => + ProjectKnowledge.layer.pipe( + Layer.provide(HolographicMemory.layer), + Layer.provideMerge( + Layer.mergeAll(ProjectStore.layer, ProjectionStore.layer, ThreadSearch.layer), + ), + Layer.provideMerge(SqlitePersistence.layerFromPath(dbPath)), + Layer.provide( + Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(environmentId), + }), + ), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + +const projectEvent = (projectId: ProjectId): ApplicationProjectEvent => ({ + sequence: 0, + eventId: EventId.make(`created:${projectId}`), + aggregateKind: "project", + aggregateId: projectId, + occurredAt: DateTime.formatIso(at), + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "project.created", + payload: { + projectId, + title: projectId, + workspaceRoot: `/replay/${projectId}`, + defaultModelSelection: null, + scripts: [], + createdAt: DateTime.formatIso(at), + updatedAt: DateTime.formatIso(at), + }, +}); + +const threadEvent = (threadId: ThreadId, projectId: ProjectId): OrchestrationV2DomainEvent => ({ + id: EventId.make(`created:${threadId}`), + type: "thread.created", + threadId, + providerInstanceId, + occurredAt: at, + payload: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId, + title: threadId, + providerInstanceId, + modelSelection: { instanceId: providerInstanceId, model: "replay" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: at, + updatedAt: at, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, +}); + +const messageEvent = ( + threadId: ThreadId, + id: string, + text: string, +): OrchestrationV2DomainEvent => ({ + id: EventId.make(`message:${id}`), + type: "message.updated", + threadId, + providerInstanceId, + occurredAt: at, + payload: { + createdBy: "user", + creationSource: "web", + id: MessageId.make(id), + threadId, + runId: null, + nodeId: null, + role: "user", + text, + attachments: [], + streaming: false, + createdAt: at, + updatedAt: at, + }, +}); + +const spans: Array<{ name: string; ms: number }> = []; +const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (endTime, exit) => { + end(endTime, exit); + spans.push({ name: span.name, ms: Number(endTime - options.startTime) / 1e6 }); + }; + return span; + }, +}); + +const stageMs = (name: string): number | null => { + const found = spans.filter((span) => span.name === name); + if (found.length === 0) return null; + return found.reduce((sum, span) => sum + span.ms, 0); +}; + +const recallGate = (outcome: ProjectKnowledge.RecallOutcome): (typeof GATES)[number] => { + switch (outcome._tag) { + case "Attached": + return "delivered"; + case "Omitted": + return outcome.reason === "timed_out" ? "timeout" : "failed"; + case "Skipped": + switch (outcome.reason) { + case "slash": + return "slash"; + case "hand_attached": + return "hand_picked"; + case "not_substantive": + return "not_substantive"; + case "no_budget": + return "allowance"; + case "no_match": + return "no_match"; + } + } +}; + +const deliveredFactIds = (outcome: ProjectKnowledge.RecallOutcome): Array => { + if (outcome._tag !== "Attached") return []; + return outcome.composer.records.flatMap((record) => { + if (record.kind !== "project-knowledge" || !("knowledge" in record)) return []; + const knowledge = record.knowledge as { + selections: ReadonlyArray<{ kind: string; factId?: string }>; + }; + return knowledge.selections.flatMap((selection) => + selection.kind === "fact" && selection.factId ? [selection.factId] : [], + ); + }); +}; + +const stamp = (value: string | null): string | null => { + if (value === null) return null; + const millis = Date.parse(value); + if (!Number.isFinite(millis)) return null; + return DateTime.formatIso(DateTime.makeUnsafe(millis)); +}; + +const loadFacts = Effect.fn("replay.loadFacts")(function* ( + facts: ReadonlyArray, + messageProjects: ReadonlyArray, +) { + const projects = yield* ProjectStore.ProjectStoreV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const sql = yield* SqlClient.SqlClient; + const projectIds = [...new Set([...facts.map((fact) => fact.projectId), ...messageProjects])]; + for (const id of projectIds) yield* projects.apply(projectEvent(ProjectId.make(id))); + const byProject = new Map>(); + for (const fact of facts) { + const group = byProject.get(fact.projectId) ?? []; + group.push(fact); + byProject.set(fact.projectId, group); + } + const stamps: Array<{ id: string; projectId: string; createdAt: string | null; trust: number }> = + []; + for (const [projectId, group] of byProject) { + const citeThread = ThreadId.make(`replay-cite:${projectId}`); + const citeMessage = `replay-cite-message:${projectId}`; + yield* projections.apply(threadEvent(citeThread, ProjectId.make(projectId))); + yield* projections.apply(messageEvent(citeThread, citeMessage, "Replay citation.")); + const source = yield* knowledge.readSource({ + projectId: ProjectId.make(projectId), + threadId: citeThread, + messageId: MessageId.make(citeMessage), + }); + if (source.state !== "available") return yield* Effect.die("replay citation did not resolve"); + for (const fact of group) { + const originThread = fact.originThread ?? citeThread; + yield* knowledge.mutate( + { + action: "create", + commandId: CommandId.make(`create:${fact.id}`), + projectId: ProjectId.make(projectId), + factId: ProjectFactId.make(fact.id), + content: fact.content, + entities: [...fact.entities], + tags: [...fact.tags], + kind: "note", + sources: [source.source], + }, + { + kind: "assisted", + threadId: ThreadId.make(originThread), + runId: RunId.make(`replay-run:${projectId}`), + runOutcome: "completed", + }, + ); + stamps.push({ + id: fact.id, + projectId, + createdAt: stamp(fact.createdAt), + trust: fact.trust ?? 0.5, + }); + } + } + yield* sql.withTransaction( + Effect.gen(function* () { + for (const fact of stamps) { + if (fact.createdAt === null && fact.trust === 0.5) continue; + if (fact.createdAt === null) { + yield* sql`UPDATE project_knowledge_facts SET trust = ${fact.trust} WHERE id = ${fact.id} AND project_id = ${fact.projectId}`; + } else { + yield* sql`UPDATE project_knowledge_facts SET created_at = ${fact.createdAt}, updated_at = ${fact.createdAt}, trust = ${fact.trust} WHERE id = ${fact.id} AND project_id = ${fact.projectId}`; + } + } + }), + ); + return facts.length; +}); + +const measureMessage = Effect.fn("replay.measureMessage")(function* (message: NormalizedMessage) { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + spans.length = 0; + const started = performance.now(); + const outcome = yield* knowledge + .recall({ + projectId: ProjectId.make(message.projectId), + threadId: ThreadId.make(message.threadId), + requestId: CommandId.make(`memory-recall:${message.messageId}`), + query: message.text, + composer: { text: message.text, records: [] }, + knowledgeAllowance: KNOWLEDGE_ALLOWANCE, + }) + .pipe(Effect.provideService(Tracer.Tracer, tracer)); + const wallMs = performance.now() - started; + const row: ReplayRow = { + messageId: message.messageId, + projectId: message.projectId, + threadId: message.threadId, + createdBy: message.createdBy, + characters: message.text.length, + gate: recallGate(outcome), + deliveredFactIds: deliveredFactIds(outcome), + wallMs, + candidatesMs: + stageMs("ProjectKnowledgeStore.recallCandidates") ?? + stageMs("ProjectKnowledgeStore.candidates"), + scoringMs: stageMs("HolographicMemory.scoreCandidates"), + resolveMs: stageMs("ProjectKnowledge.resolveMatches"), + seenMs: stageMs("ProjectKnowledgeStore.seenFactIds"), + }; + return row; +}); + +export const replayProjectMemory = Effect.fn("replay.projectMemory")(function* ( + options: ReplayOptions, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + for (const file of [options.facts, options.messages, options.out]) assertReplayPath(path, file); + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-memory-replay-" }); + const dbPath = path.join(directory, "state.sqlite"); + assertReplayPath(path, dbPath); + const facts = parseJsonArray(yield* fs.readFileString(options.facts)).map(normalizeFact); + const messages = parseJsonArray(yield* fs.readFileString(options.messages)).map(normalizeMessage); + const corpus = selectCorpus(facts, messages, options); + const produced = yield* Effect.gen(function* () { + const loaded = yield* loadFacts( + corpus.facts, + corpus.messages.map((message) => message.projectId), + ); + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const warmupProject = corpus.messages[0]?.projectId ?? corpus.facts[0]?.projectId; + if (warmupProject !== undefined) { + spans.length = 0; + yield* knowledge + .recall({ + projectId: ProjectId.make(warmupProject), + threadId: ThreadId.make("replay-warmup-thread"), + requestId: CommandId.make("memory-recall:warmup"), + query: "warmup cache tenant isolation keys", + composer: { text: "warmup cache tenant isolation keys", records: [] }, + knowledgeAllowance: KNOWLEDGE_ALLOWANCE, + }) + .pipe(Effect.provideService(Tracer.Tracer, tracer)); + } + const rows: ReplayRow[] = []; + for (const message of corpus.messages) rows.push(yield* measureMessage(message)); + return { loaded, rows }; + }).pipe(Effect.provide(knowledgeLayer(dbPath))); + const summary = summarizeReplay(produced.rows, { + factsLoaded: produced.loaded, + factScale: corpus.factScale, + project: corpus.project, + knowledgeAllowance: KNOWLEDGE_ALLOWANCE, + recallTimeout: RECALL_TIMEOUT, + citation: + "one shared resolving message per project; assisted origin uses origin_thread when the export has one", + warmupExcluded: 1, + }); + yield* fs.makeDirectory(options.out, { recursive: true }); + const lines = produced.rows.map((row) => encodeJson(row)); + yield* fs.writeFileString( + path.join(options.out, "results.ndjson"), + lines.join("\n") + (lines.length > 0 ? "\n" : ""), + ); + yield* fs.writeFileString(path.join(options.out, "summary.json"), `${encodePretty(summary)}\n`); + return { rows: produced.rows, summary }; +}); + +const isCli = + process.argv[1] !== undefined && import.meta.url === NodeURL.pathToFileURL(process.argv[1]).href; +if (isCli) { + Effect.runPromise( + replayProjectMemory(parseReplayArgs(process.argv)).pipe( + Effect.scoped, + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ) + .then(({ summary }) => { + process.stdout.write( + `${JSON.stringify({ + messages: summary.messages, + byGate: summary.byGate, + lookupLatencyMs: summary.lookupLatencyMs, + exceededMs: summary.exceededMs, + })}\n`, + ); + }) + .catch((error: unknown) => { + const message = error instanceof Error ? error.message : "replay failed"; + process.stderr.write(`${message}\n`); + process.exitCode = 1; + }); +} diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index bdff8aef406c9..f1cd03a4ce75f 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -1306,7 +1306,9 @@ function makeLocalCommandHarness(input: { Layer.provide( Layer.mergeAll( Layer.mock(ProjectKnowledge.ProjectKnowledge)({ - recall: input.recallKnowledge ?? (() => Effect.succeed(null)), + recall: + input.recallKnowledge ?? + (() => Effect.succeed({ _tag: "Skipped", reason: "no_match" })), recordViews: input.recordKnowledgeViews ?? (() => Effect.void), ...(input.resolveKnowledge ? { resolveForTurn: input.resolveKnowledge } : {}), readSentDeliveries: input.readSentDeliveries ?? (() => Effect.succeed([])), @@ -2292,8 +2294,11 @@ effectIt.effect.each(["current", "stale", "stale-before-dispatch"] as const)( }; const recall = vi.fn((input) => Effect.succeed({ - text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, - records: [...input.composer.records, record], + _tag: "Attached", + composer: { + text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, + records: [...input.composer.records, record], + }, }), ); for (const [source, ordinal] of [ @@ -2629,7 +2634,7 @@ effectIt.effect.each([ for (const id of factIds) viewed.add(id); }), recallKnowledge: (input) => { - if (viewed.has(factId)) return Effect.succeed(null); + if (viewed.has(factId)) return Effect.succeed({ _tag: "Skipped", reason: "no_match" }); const record = { version: 1 as const, kind: "project-knowledge" as const, @@ -2638,8 +2643,11 @@ effectIt.effect.each([ knowledge: context, }; return Effect.succeed({ - text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, - records: [...input.composer.records, record], + _tag: "Attached", + composer: { + text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, + records: [...input.composer.records, record], + }, }); }, resolveKnowledge: (context) => @@ -3556,8 +3564,11 @@ effectIt.effect.each([false, true, "with-recall"] as const)( label: "Recalled project memory", }; return Effect.succeed({ - text: `${input.composer.text}\n\n${formatComposerContextReference(recalled)}`, - records: [...input.composer.records, recalled], + _tag: "Attached", + composer: { + text: `${input.composer.text}\n\n${formatComposerContextReference(recalled)}`, + records: [...input.composer.records, recalled], + }, }); }, } @@ -3691,8 +3702,11 @@ const knowledgeRetryHarness = ( input: Parameters[0], ) => Effect.succeed({ - text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, - records: [...input.composer.records, record], + _tag: "Attached", + composer: { + text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, + records: [...input.composer.records, record], + }, }), } : {}), @@ -4094,6 +4108,38 @@ effectIt.effect("records a delivery receipt when every attached knowledge record [{ contextId: record.contextId, label: record.label, reason: "not_referenced" }], ]), ); + + const timedOut = makeLocalCommandHarness({ + text: "Review SQLite migrations for project memory.", + previousTurn: { runStatus: "completed", turnStatus: "completed" }, + recallKnowledge: () => Effect.succeed({ _tag: "Omitted", reason: "timed_out" }), + }); + yield* timedOut.start; + const timedOutStart = timedOut.startRootRun.mock.calls[0]![0]; + yield* timedOutStart.session.startTurn({ + appThread: timedOutStart.appThread, + threadId: timedOutStart.appThread.id, + runId: timedOutStart.run.id, + runOrdinal: timedOutStart.run.ordinal, + providerTurnOrdinal: timedOutStart.providerTurnOrdinal, + attemptId: timedOutStart.attemptId, + rootNodeId: timedOutStart.rootNode.id, + providerThread: timedOutStart.providerThread, + message: timedOutStart.message, + modelSelection: timedOutStart.modelSelection, + runtimePolicy: timedOutStart.runtimePolicy, + }); + expect(timedOut.nativeStart).toHaveBeenCalled(); + expect(timedOut.knowledgeDeliveries.at(-1)).toMatchObject({ + status: "sent", + omissions: [ + { + contextId: ComposerContextId.make("recall"), + label: "Recalled project memory", + reason: "recall_failed", + }, + ], + }); }), ); @@ -4110,7 +4156,8 @@ effectIt.effect.each(["none", "overlap", "mixed"] as const)( text: "Continue on the new provider", previousTurn: { runStatus: "completed", turnStatus: "completed" }, recallKnowledge: (input) => { - if (recallMode === "none" || recalled) return Effect.succeed(null); + if (recallMode === "none" || recalled) + return Effect.succeed({ _tag: "Skipped", reason: "no_match" }); recalled = true; const record = { version: 1 as const, @@ -4131,8 +4178,11 @@ effectIt.effect.each(["none", "overlap", "mixed"] as const)( }, }; return Effect.succeed({ - text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, - records: [...input.composer.records, record], + _tag: "Attached", + composer: { + text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, + records: [...input.composer.records, record], + }, }); }, // The fact was edited after the earlier message was sent; the handoff must not re-hydrate. diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 292b25ae91400..bd5db353885c3 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -7,6 +7,7 @@ import { prepareKnowledgeDelivery } from "../project/knowledge/delivery.ts"; import { ConversationSummaryRuntime } from "../project/conversationSummaries/conversationSummarySchedule.ts"; import { CommandId, + ComposerContextId, latestProviderTurnForAttempt, type OrchestrationV2DomainEvent, type OrchestrationV2ContextHandoff, @@ -1945,34 +1946,46 @@ export const layer: Layer.Layer< { // Recall adds related saved facts to the message, so no one has to pick them by hand. // Its text tells the agent to call T3 tools, so a session without them gets none. - const recalled = - !supportsT3Tools || noteContinuation || initialDeliveryState.sent - ? null - : yield* knowledge.recall({ - projectId: projection.thread.projectId, - threadId: projection.thread.id, - requestId: CommandId.make(`memory-recall:${attempt.id}`), - query: providerMessage.text, - composer: pstackComposer, - knowledgeAllowance: budget.knowledgeAllowance, - turn: { - messageId: message.id, - attemptId: attempt.id, - providerInstanceId: run.providerInstanceId, - providerThreadId: runningProviderThread.id, - nativeThreadId: runningProviderThread.nativeThreadRef?.nativeId ?? null, - }, + if (supportsT3Tools && !noteContinuation && !initialDeliveryState.sent) { + const recalled = yield* knowledge.recall({ + projectId: projection.thread.projectId, + threadId: projection.thread.id, + requestId: CommandId.make(`memory-recall:${attempt.id}`), + query: providerMessage.text, + composer: pstackComposer, + knowledgeAllowance: budget.knowledgeAllowance, + turn: { + messageId: message.id, + attemptId: attempt.id, + providerInstanceId: run.providerInstanceId, + providerThreadId: runningProviderThread.id, + nativeThreadId: runningProviderThread.nativeThreadRef?.nativeId ?? null, + }, + }); + switch (recalled._tag) { + case "Attached": { + const withRecall = yield* prepareDelivery(recalled.composer).pipe(Effect.option); + if (Option.isSome(withRecall)) { + recalledComposer = recalled.composer; + knowledgeDelivery = withRecall.value; + composer = knowledgeDelivery.composer; + initialDeliveryState = yield* knowledgeDelivery.readState; + userText = initialDeliveryState.sent ? composer.baseText : composer.text; + } + break; + } + case "Omitted": + composer.omissions.push({ + contextId: ComposerContextId.make("recall"), + label: "Recalled project memory", + reason: "recall_failed", }); - const withRecall = - recalled === null - ? Option.none() - : yield* prepareDelivery(recalled).pipe(Effect.option); - if (Option.isSome(withRecall)) { - recalledComposer = recalled; - knowledgeDelivery = withRecall.value; - composer = knowledgeDelivery.composer; - initialDeliveryState = yield* knowledgeDelivery.readState; - userText = initialDeliveryState.sent ? composer.baseText : composer.text; + break; + case "Skipped": + break; + default: + recalled satisfies never; + } } yield* knowledgeDelivery.checkBudget(budget, initialDeliveryState.sent); if (!(yield* isCurrentAttemptInStatus("running"))) return; diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 93edb4447252e..2c0a31c783d91 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -528,7 +528,7 @@ export function layerWithRegistry( Effect.succeed({ sent: false, sentThisAttempt: false, uncertain: false }), readSentDeliveries: () => Effect.succeed([]), recordViews: () => Effect.void, - recall: () => Effect.succeed(null), + recall: () => Effect.succeed({ _tag: "Skipped", reason: "no_match" }), }), layerContextHandoffServiceProvided, layerEventSinkProvided, diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts index f9019e901aa83..385accd092733 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts @@ -35,6 +35,7 @@ import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import * as Tracer from "effect/Tracer"; import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts"; import * as McpInvocationContext from "../../mcp/McpInvocationContext.ts"; import * as McpToolAccess from "../../mcp/McpToolAccess.ts"; @@ -203,6 +204,20 @@ const message = ( }, }); +const attachedComposer = (outcome: ProjectKnowledge.RecallOutcome) => + outcome._tag === "Attached" ? outcome.composer : null; + +const attachedFactIds = (outcome: ProjectKnowledge.RecallOutcome) => { + const composer = attachedComposer(outcome); + return (composer?.records ?? []).flatMap((record) => + record.kind === "project-knowledge" && "knowledge" in record + ? record.knowledge.selections.flatMap((selection) => + selection.kind === "fact" ? [selection.factId] : [], + ) + : [], + ); +}; + const createFact = (projectId: ProjectId, id = "fact-one") => ({ action: "create", @@ -1767,14 +1782,16 @@ it.effect("browsing searches can opt out of reinforcing retrieval counts", () => (listed) => listed.facts[0]?.retrievalCount, ); const recalled = Effect.fn("test.recalled")(function* (requestId: string, query: string) { - const composer = yield* knowledge.recall({ - projectId, - threadId: ThreadId.make("recall-thread"), - requestId: CommandId.make(requestId), - query, - composer: { text: query, records: [] }, - knowledgeAllowance: 48000, - }); + const composer = attachedComposer( + yield* knowledge.recall({ + projectId, + threadId: ThreadId.make("recall-thread"), + requestId: CommandId.make(requestId), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }), + ); const record = composer?.records.find((item) => item.kind === "project-knowledge"); return record?.kind === "project-knowledge" && "knowledge" in record ? record.knowledge.selections.flatMap((selection) => @@ -1843,15 +1860,17 @@ it.effect( overrides: Partial[0]> = {}, requestId = "recall", ) => - knowledge.recall({ - projectId, - threadId, - requestId: CommandId.make(requestId), - query, - composer: { text: query, records: [] }, - knowledgeAllowance: 48000, - ...overrides, - }); + knowledge + .recall({ + projectId, + threadId, + requestId: CommandId.make(requestId), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + ...overrides, + }) + .pipe(Effect.map(attachedComposer)); const recalled = yield* recall(); const record = recalled?.records[0]; @@ -1988,14 +2007,16 @@ it.effect("does not recall a fact the thread's agent has already been shown", () for (const [id, content] of Object.entries(contents)) yield* knowledge.mutate({ ...createFact(projectId, id), content }, { kind: "user" }); const recall = (threadId: ThreadId, requestId: string) => - knowledge.recall({ - projectId, - threadId, - requestId: CommandId.make(requestId), - query, - composer: { text: query, records: [] }, - knowledgeAllowance: 48000, - }); + knowledge + .recall({ + projectId, + threadId, + requestId: CommandId.make(requestId), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }) + .pipe(Effect.map(attachedComposer)); const recalledIn = Effect.fn("test.recalledIn")(function* (thread: string, request = thread) { const composer = yield* recall(ThreadId.make(thread), `recall-${request}`); return (composer?.records ?? []).flatMap((record) => @@ -2186,14 +2207,16 @@ it.effect("recalls unseen facts beyond a full page of facts the thread has read" ids.slice(0, 9), ); const query = "Change cache keys to include tenant IDs."; - const recalled = yield* knowledge.recall({ - projectId, - threadId, - requestId: CommandId.make("recall-after-first-page"), - query, - composer: { text: query, records: [] }, - knowledgeAllowance: 48000, - }); + const recalled = attachedComposer( + yield* knowledge.recall({ + projectId, + threadId, + requestId: CommandId.make("recall-after-first-page"), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }), + ); const record = recalled?.records[0]; assert.equal(record?.kind, "project-knowledge"); if (record?.kind !== "project-knowledge" || !("knowledge" in record)) return; @@ -2203,6 +2226,128 @@ it.effect("recalls unseen facts beyond a full page of facts the thread has read" }).pipe(Effect.provide(layerTest)), ); +it.effect("recall keeps the most trusted fact when more than the bound match equally", () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const sql = yield* SqlClient.SqlClient; + const projectId = ProjectId.make("recall-trust-tie"); + yield* createProject(projectId); + const ids = Array.from({ length: 41 }, (_, index) => + ProjectFactId.make(`tie-${index.toString().padStart(2, "0")}`), + ); + for (const factId of ids) + yield* knowledge.mutate(createFact(projectId, factId), { kind: "user" }); + yield* sql`UPDATE project_knowledge_facts SET trust = 1 WHERE id = ${ids[40]!}`; + const query = "Change cache keys to include tenant IDs."; + const outcome = yield* knowledge.recall({ + projectId, + threadId: ThreadId.make("recall-trust-tie"), + requestId: CommandId.make("recall-trust-tie"), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }); + assert.equal(attachedFactIds(outcome)[0], ids[40]); + }).pipe(Effect.provide(layerTest)), +); + +it.effect( + "recall attaches an older fact when closer matches were shown or came from this thread", + () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const query = "Change cache keys to include tenant IDs."; + const longer = "Cache keys include tenant IDs. " + "background note ".repeat(40); + const recallTarget = (projectId: ProjectId, threadId: ThreadId, requestId: string) => + knowledge.recall({ + projectId, + threadId, + requestId: CommandId.make(requestId), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }); + const saveOlderTarget = (projectId: ProjectId) => { + const factId = ProjectFactId.make(`${projectId}-target`); + return Effect.gen(function* () { + yield* createProject(projectId); + yield* knowledge.mutate( + { + ...createFact(projectId, factId), + commandId: CommandId.make(`create:${factId}`), + content: longer, + }, + { kind: "user" }, + ); + yield* TestClock.adjust("1 minute"); + return factId; + }); + }; + + const shownProject = ProjectId.make("recall-older-shown"); + const shownThread = ThreadId.make("recall-older-shown"); + const shownTarget = yield* saveOlderTarget(shownProject); + const shownIds = Array.from({ length: 45 }, (_, index) => + ProjectFactId.make(`shown-${index.toString().padStart(2, "0")}`), + ); + for (const factId of shownIds) + yield* knowledge.mutate(createFact(shownProject, factId), { kind: "user" }); + yield* knowledge.recordViews(shownProject, shownThread, shownIds); + assert.deepEqual( + attachedFactIds(yield* recallTarget(shownProject, shownThread, "recall-older-shown")), + [shownTarget], + ); + + const citedProject = ProjectId.make("recall-older-cited"); + const citedThread = ThreadId.make("recall-older-cited"); + const citedTarget = yield* saveOlderTarget(citedProject); + yield* projections.apply(thread(citedThread, citedProject)); + yield* projections.apply( + message(citedThread, "recall-older-cited-message", "user", "tenant IDs in keys"), + ); + const source = yield* knowledge.readSource({ + projectId: citedProject, + threadId: citedThread, + messageId: MessageId.make("recall-older-cited-message"), + }); + if (source.state !== "available") return yield* Effect.die("source unavailable"); + for (let index = 0; index < 45; index++) + yield* knowledge.mutate( + { + ...createFact(citedProject, `cited-${index.toString().padStart(2, "0")}`), + sources: [source.source], + }, + { kind: "user" }, + ); + assert.deepEqual( + attachedFactIds(yield* recallTarget(citedProject, citedThread, "recall-older-cited")), + [citedTarget], + ); + + const originProject = ProjectId.make("recall-older-origin"); + const originThread = ThreadId.make("recall-older-origin"); + const originTarget = yield* saveOlderTarget(originProject); + const origin = { + kind: "agent-thread" as const, + threadId: originThread, + providerInstanceId, + }; + for (let index = 0; index < 45; index++) + yield* knowledge.mutate( + { + ...createFact(originProject, `origin-${index.toString().padStart(2, "0")}`), + sources: [], + }, + origin, + ); + assert.deepEqual( + attachedFactIds(yield* recallTarget(originProject, originThread, "recall-older-origin")), + [originTarget], + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect("checks citations for one page of recall, not for every ranked fact", () => Effect.gen(function* () { const knowledge = yield* ProjectKnowledge.ProjectKnowledge; @@ -3165,22 +3310,195 @@ it.effect("automatic corroboration appends validated sources without rewriting c ); it.effect( - "recall selects two related facts without searching transcripts or recording retrieval", + "returns a timed-out outcome when a recall store read is still open after one second", () => Effect.gen(function* () { const knowledge = yield* ProjectKnowledge.ProjectKnowledge; - const projectId = ProjectId.make("bounded-recall"); - const query = "cache keys tenant"; + const projectId = ProjectId.make("recall-timeout"); yield* createProject(projectId); - const recall = (requestId: string) => - knowledge.recall({ + yield* knowledge.mutate(createFact(projectId), { kind: "user" }); + const blocked = yield* Deferred.make(); + const stall: Statement.Transformer = (statement) => + Deferred.await(blocked).pipe(Effect.as(statement)); + const query = "Change cache keys to include tenant IDs."; + const pending = yield* knowledge + .recall({ projectId, - threadId: ThreadId.make("recall-thread"), - requestId: CommandId.make(requestId), + threadId: ThreadId.make("recall-timeout"), + requestId: CommandId.make("recall-timeout"), query, composer: { text: query, records: [] }, knowledgeAllowance: 48000, - }); + }) + .pipe(Effect.provideService(Statement.CurrentTransformer, stall), Effect.forkChild); + yield* TestClock.adjust("999 millis"); + assert.isUndefined(pending.pollUnsafe()); + yield* TestClock.adjust("1 millis"); + assert.deepEqual(yield* Fiber.join(pending), { + _tag: "Omitted", + reason: "timed_out", + }); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("does not consider a newer fact that shares no term with the recall query", () => { + const considered: string[] = []; + const scoring = Layer.succeed(HolographicMemory.HolographicMemory, { + scoreCandidates: (input) => + Effect.sync(() => { + considered.push(...input.candidates.map((candidate) => candidate.id)); + return input.candidates.map((candidate) => ({ + id: candidate.id, + rawCosine: 1, + holographic: 1, + decay: 1, + reinforcement: 0, + score: 1, + scoreMillionths: 1_000_000, + tokenOverlap: 1, + fts: 1, + coverage: 1, + })); + }), + }); + return Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const sql = yield* SqlClient.SqlClient; + const projectId = ProjectId.make("recall-bounded"); + yield* createProject(projectId); + yield* knowledge.mutate(createFact(projectId, "matching"), { kind: "user" }); + yield* TestClock.adjust("1 minute"); + yield* knowledge.mutate( + { + ...createFact(projectId, "newer-unrelated"), + content: "Zephyr quilting marmalade weekday.", + entities: [], + tags: [], + }, + { kind: "user" }, + ); + const query = "Change cache keys to include tenant IDs."; + yield* knowledge.recall({ + projectId, + threadId: ThreadId.make("recall-bounded"), + requestId: CommandId.make("recall-bounded"), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }); + assert.include(considered, "matching"); + assert.notInclude(considered, "newer-unrelated"); + const searched = yield* knowledge.search({ + projectId, + query, + requestId: CommandId.make("search-bounded"), + }); + assert.equal(searched.facts.state, "available"); + if (searched.facts.state !== "available") return; + assert.include( + searched.facts.matches.map((match) => match.fact.id), + ProjectFactId.make("newer-unrelated"), + ); + assert.deepEqual( + yield* sql`SELECT id FROM project_knowledge_facts WHERE id = 'newer-unrelated' AND updated_at > (SELECT updated_at FROM project_knowledge_facts WHERE id = 'matching')`, + [{ id: "newer-unrelated" }], + ); + }).pipe(Effect.provide(knowledgeTestLayer(scoring))); +}); + +it.effect("reads the recall lookup on the reader connection", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-recall-reader-" }); + const layerFile = ProjectKnowledge.layer.pipe( + Layer.provide(HolographicMemory.layer), + Layer.provideMerge( + Layer.mergeAll(ProjectStore.layer, ProjectionStore.layer, ThreadSearch.layer), + ), + Layer.provideMerge(SqlitePersistence.layerFromPath(path.join(directory, "state.sqlite"))), + Layer.provide( + Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(environmentId), + }), + ), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + const spans: Array = []; + const observe: Statement.Transformer = (statement, _sql, _fiber, span) => { + spans.push(span); + return Effect.succeed(statement); + }; + yield* Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const projectId = ProjectId.make("recall-reader"); + yield* createProject(projectId); + yield* knowledge.mutate(createFact(projectId), { kind: "user" }); + const query = "Change cache keys to include tenant IDs."; + yield* knowledge + .recall({ + projectId, + threadId: ThreadId.make("recall-reader"), + requestId: CommandId.make("recall-reader"), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }) + .pipe( + Effect.withTracerEnabled(true), + Effect.provideService(Statement.CurrentTransformer, observe), + Effect.provideService(Statement.SpanPropagationEnabled, true), + ); + const connectionOf = (span: Tracer.Span): unknown => { + const own = span.attributes.get("db.connection"); + if (typeof own === "string") return own; + const parent = span.parent._tag === "Some" ? span.parent.value : undefined; + return parent?._tag === "Span" ? connectionOf(parent) : own; + }; + const connections = spans.map((span) => { + const parent = span.parent._tag === "Some" ? span.parent.value : undefined; + return { + name: parent?._tag === "Span" ? parent.name : span.name, + connection: connectionOf(span), + }; + }); + assert.isAbove(connections.length, 0); + assert.isTrue( + connections.every((span) => span.connection === "reader"), + JSON.stringify(connections), + ); + for (const name of [ + "ProjectKnowledgeStore.seenFactIds", + "ProjectKnowledgeStore.recallCandidates", + "ProjectKnowledgeStore.find", + ]) + assert.isTrue( + connections.some((span) => span.name === name), + JSON.stringify(connections), + ); + }).pipe(Effect.provide(layerFile)); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect( + "recall selects two related facts without searching transcripts or recording retrieval", + () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const projectId = ProjectId.make("bounded-recall"); + const query = "cache keys tenant"; + yield* createProject(projectId); + const recall = (requestId: string) => + knowledge + .recall({ + projectId, + threadId: ThreadId.make("recall-thread"), + requestId: CommandId.make(requestId), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }) + .pipe(Effect.map(attachedComposer)); assert.isNull(yield* recall("recall-empty")); for (const id of ["first", "second", "third"]) yield* knowledge.mutate(createFact(projectId, id), { kind: "user" }); diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.ts b/apps/server/src/project/knowledge/ProjectKnowledge.ts index 766741a9fe189..f2f93faa1acb4 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.ts @@ -51,6 +51,7 @@ import * as Layer from "effect/Layer"; import * as Cause from "effect/Cause"; import * as Option from "effect/Option"; import * as SqlClient from "effect/sql/SqlClient"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import * as ProjectStore from "../../orchestration-v2/ProjectStore.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; @@ -72,12 +73,20 @@ type RecallComposer = { readonly text: string; readonly records: ReadonlyArray; }; + +export type RecallOutcome = + | { readonly _tag: "Attached"; readonly composer: RecallComposer } + | { + readonly _tag: "Skipped"; + readonly reason: "slash" | "hand_attached" | "not_substantive" | "no_budget" | "no_match"; + } + | { readonly _tag: "Omitted"; readonly reason: "timed_out" | "failed" }; const RECALL_CONTEXT_ID = ComposerContextId.make("recall"); /** Recall sends memory in a shorter form than knowledge someone attached by hand. */ export const isRecalledMemory = (record: { readonly contextId: string }) => record.contextId === RECALL_CONTEXT_ID; -// Recall runs before every eligible turn, so it gives up on a slow store instead of waiting. -const RECALL_TIMEOUT = "150 millis"; +// Recall runs before every eligible turn. A stalled lookup reports an omission and the turn starts. +const RECALL_TIMEOUT = "1 second"; // The most bytes recall adds to a turn. The envelope reserve covers the wrapper around the // facts, so the delivery's own budget check cannot refuse what recall accepted. const RECALL_MAX_BYTES = 4096; @@ -142,8 +151,7 @@ export class ProjectKnowledge extends Context.Service< ) => Effect.Effect; /** * Finds saved facts related to a user message that the thread's agent has not seen yet, and - * attaches them as a knowledge record for the turn's delivery to send. Returns null when - * nothing fits, when the lookup fails or is slow, or when the user attached knowledge by hand. + * attaches them as a knowledge record for the turn's delivery to send. */ readonly recall: (input: { readonly projectId: ProjectId; @@ -155,7 +163,7 @@ export class ProjectKnowledge extends Context.Service< readonly knowledgeAllowance: number; /** The message being sent and the native conversation it targets. */ readonly turn?: Omit; - }) => Effect.Effect; + }) => Effect.Effect; readonly prepareContext: ( input: ProjectKnowledgeContext, ) => Effect.Effect; @@ -904,7 +912,11 @@ const make = Effect.gen(function* () { // Recall keeps its best two matches after removing facts the thread has already seen. function* ( request: ProjectKnowledgeSearchInput, - recallOptions?: { readonly skip: (fact: ProjectFact) => boolean }, + recallOptions?: { + readonly skip: (fact: ProjectFact) => boolean; + readonly threadId: ThreadId; + readonly excludeFactIds: ReadonlyArray; + }, ): Effect.fn.Return { const skip = recallOptions?.skip; const { @@ -1000,15 +1012,23 @@ const make = Effect.gen(function* () { } let ranking = rootReceipt?.search?.ranking ?? null; if (ranking === null) { - const candidates = yield* store - .candidates( - input.projectId, - projectMemorySearchTokens(input.query), - entities, - minTrust, - input.includeSuperseded ?? false, - ) - .pipe(Effect.mapError(storageError(input.projectId))); + const candidates = yield* ( + recallOptions === undefined + ? store.candidates( + input.projectId, + projectMemorySearchTokens(input.query), + entities, + minTrust, + input.includeSuperseded ?? false, + ) + : store.recallCandidates( + input.projectId, + projectMemorySearchTokens(input.query), + minTrust, + recallOptions.threadId, + recallOptions.excludeFactIds, + ) + ).pipe(Effect.mapError(storageError(input.projectId))); const eligible = candidates.facts.filter( (fact): fact is typeof ActiveProjectFact.Type => fact.status !== "forgotten" && @@ -1271,17 +1291,29 @@ const make = Effect.gen(function* () { }); const recall: ProjectKnowledge["Service"]["recall"] = Effect.fn("ProjectKnowledge.recall")( function* (input) { - if ( - input.composer.records.some((record) => record.kind === "project-knowledge") || - input.query.trimStart().startsWith("/") || - !isSubstantiveProjectMemoryQuery(input.query) - ) - return null; + const note = (outcome: RecallOutcome) => + Effect.annotateCurrentSpan( + "recall.outcome", + outcome._tag === "Attached" ? "attached" : outcome.reason, + ).pipe(Effect.as(outcome)); + const omit = (reason: "timed_out" | "failed") => + Effect.logWarning("Project memory recall failed", { + projectId: input.projectId, + threadId: input.threadId, + reason, + }).pipe(Effect.andThen(note({ _tag: "Omitted", reason }))); + if (input.composer.records.some((record) => record.kind === "project-knowledge")) + return yield* note({ _tag: "Skipped", reason: "hand_attached" }); + if (input.query.trimStart().startsWith("/")) + return yield* note({ _tag: "Skipped", reason: "slash" }); + if (!isSubstantiveProjectMemoryQuery(input.query)) + return yield* note({ _tag: "Skipped", reason: "not_substantive" }); const factBytes = Math.min( RECALL_MAX_BYTES, Math.floor(input.knowledgeAllowance) - RECALL_ENVELOPE_BYTES, ); - if (factBytes < RECALL_MIN_BYTES) return null; + if (factBytes < RECALL_MIN_BYTES) + return yield* note({ _tag: "Skipped", reason: "no_budget" }); const lookup = Effect.gen(function* () { const seen = yield* store .seenFactIds(input.projectId, input.threadId, input.turn) @@ -1294,9 +1326,13 @@ const make = Effect.gen(function* () { recordRetrieval: false, minTrust: 0.5, }, - { skip: (fact) => seen.has(fact.id) || cameFromThread(fact, input.threadId) }, + { + skip: (fact) => seen.has(fact.id) || cameFromThread(fact, input.threadId), + threadId: input.threadId, + excludeFactIds: [...seen], + }, ); - if (result.facts.state !== "available") return null; + if (result.facts.state !== "available") return yield* omit("failed"); const selections = result.facts.matches.map(({ fact }) => ({ kind: "fact" as const, factId: fact.id, @@ -1323,22 +1359,20 @@ const make = Effect.gen(function* () { ).pipe(Effect.option); if (Option.isSome(resolved)) return { - text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, - records: [...input.composer.records, record], + _tag: "Attached" as const, + composer: { + text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, + records: [...input.composer.records, record], + }, }; } - return null; - }); + return { _tag: "Skipped" as const, reason: "no_match" as const }; + }).pipe(NodeSqliteClient.readOnly); return yield* lookup.pipe( Effect.timeoutOption(RECALL_TIMEOUT), - Effect.map(Option.getOrNull), + Effect.flatMap((value) => (Option.isNone(value) ? omit("timed_out") : note(value.value))), Effect.catchCause((cause) => - Cause.hasInterrupts(cause) - ? Effect.interrupt - : Effect.logWarning("Project memory recall failed", { - projectId: input.projectId, - threadId: input.threadId, - }).pipe(Effect.as(null)), + Cause.hasInterrupts(cause) ? Effect.interrupt : omit("failed"), ), ); }, diff --git a/apps/server/src/project/knowledge/persistence.ts b/apps/server/src/project/knowledge/persistence.ts index 8503c246e5679..6374cdc0f9d60 100644 --- a/apps/server/src/project/knowledge/persistence.ts +++ b/apps/server/src/project/knowledge/persistence.ts @@ -156,6 +156,11 @@ const withoutForgotten = ( ); }; +const ftsMatch = (terms: ReadonlyArray) => + terms + .map((term) => `"${term.replaceAll('"', '""')}"${Buffer.byteLength(term) >= 4 ? "*" : ""}`) + .join(" OR "); + export const makeStore = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const columns = sql` @@ -276,9 +281,7 @@ export const makeStore = Effect.gen(function* () { ) { const recallable = sql`f.status = 'saved' AND f.trust >= ${minTrust} AND (${includeSuperseded ? 1 : 0} = 1 OR f.superseded_by_id IS NULL)`; - const ftsQuery = terms - .map((term) => `"${term.replaceAll('"', '""')}"${Buffer.byteLength(term) >= 4 ? "*" : ""}`) - .join(" OR "); + const ftsQuery = ftsMatch(terms); const lexical = ftsQuery === "" ? [] @@ -306,6 +309,45 @@ export const makeStore = Effect.gen(function* () { partial: ids.length > 1000, }; }); + const recallCandidates = Effect.fn("ProjectKnowledgeStore.recallCandidates")(function* ( + projectId: ProjectId, + terms: ReadonlyArray, + minTrust: number, + threadId: ThreadId, + excludeFactIds: ReadonlyArray, + ) { + const ftsQuery = ftsMatch(terms); + if (ftsQuery === "") + return { facts: [], ranks: new Map(), partial: false }; + const unseen = + excludeFactIds.length === 0 + ? sql`1 = 1` + : sql`f.id NOT IN (SELECT value FROM json_each(${encodeFactIds(excludeFactIds)}))`; + const rows = yield* sql<{ readonly id: ProjectFactId; readonly rank: number }>` + SELECT f.id, bm25(project_knowledge_fts) AS rank + FROM project_knowledge_fts JOIN project_knowledge_facts f ON f.rowid = project_knowledge_fts.rowid + WHERE project_knowledge_fts MATCH ${ftsQuery} AND f.project_id = ${projectId} + AND f.status = 'saved' AND f.trust >= ${minTrust} AND f.superseded_by_id IS NULL + AND ${unseen} + AND NOT ( + json_extract(f.origin_json, '$.kind') IN ('agent-thread', 'assisted') + AND json_extract(f.origin_json, '$.threadId') = ${threadId} + ) + AND NOT EXISTS ( + SELECT 1 FROM json_each(f.sources_json) source + WHERE json_extract(source.value, '$.kind') = 'message' + AND json_extract(source.value, '$.threadId') = ${threadId} + ) + ORDER BY rank ASC, f.trust DESC, f.updated_at DESC, f.id ASC LIMIT 40`; + return { + facts: yield* findMany( + projectId, + rows.map((row) => row.id), + ), + ranks: new Map(rows.map((row) => [row.id, row.rank])), + partial: false, + }; + }); const findDuplicateContent = Effect.fn("ProjectKnowledgeStore.findDuplicateContent")(function* ( projectId: ProjectId, content: string, @@ -770,6 +812,7 @@ export const makeStore = Effect.gen(function* () { record, recordSearch, candidates, + recallCandidates, similar, findDuplicateContent, recordHistory, diff --git a/knip.jsonc b/knip.jsonc index bf08911f64a48..41dab0ddd4f19 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -57,6 +57,7 @@ "scripts/cli.ts", "scripts/fetch-expo-schema.ts", "scripts/probe-claude-fork-local-rollback-replay.ts", + "scripts/replay-project-memory.ts", "scripts/update-test-shard-weights.ts", "scripts/verify-background-live.ts", "src/provider/testFixtures/*.mjs",