@tangle-network/agent-knowledge 19.1.2 → 20.0.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.
- package/CHANGELOG.md +32 -2
- package/README.md +17 -91
- package/dist/benchmarks/index.d.ts +2 -2
- package/dist/benchmarks/index.js +2 -2
- package/dist/benchmarks-jir3ZP-M.js +162 -0
- package/dist/benchmarks-jir3ZP-M.js.map +1 -0
- package/dist/cli.js +2 -3
- package/dist/cli.js.map +1 -1
- package/dist/index-BhvSH4E4.d.ts +512 -0
- package/dist/index-BhvSH4E4.d.ts.map +1 -0
- package/dist/index-OAxtm6is.d.ts +9 -0
- package/dist/index-OAxtm6is.d.ts.map +1 -0
- package/dist/index.d.ts +197 -1332
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +561 -3653
- package/dist/index.js.map +1 -1
- package/dist/{inspect-C6c4zuKp.js → inspect-CMigdsD5.js} +282 -24
- package/dist/inspect-CMigdsD5.js.map +1 -0
- package/dist/memory/index.d.ts +3 -3
- package/dist/memory/index.js +3 -3
- package/dist/memory-BH6oT1Qe.js +2728 -0
- package/dist/memory-BH6oT1Qe.js.map +1 -0
- package/dist/source-record-CdWvzvO6.js +39 -0
- package/dist/source-record-CdWvzvO6.js.map +1 -0
- package/dist/types-BWV_Fvp7.d.ts +224 -0
- package/dist/types-BWV_Fvp7.d.ts.map +1 -0
- package/dist/{types-m2QB86fF.d.ts → types-BekdNwGD.d.ts} +4 -19
- package/dist/types-BekdNwGD.d.ts.map +1 -0
- package/dist/viz/index.d.ts +1 -1
- package/docs/architecture.md +2 -30
- package/docs/eval/investment-material-facts.md +2 -0
- package/docs/results/research-driving.md +8 -8
- package/docs/verified-research-ab.md +12 -10
- package/package.json +6 -12
- package/skills/build-with-agent-knowledge/SKILL.md +2 -15
- package/dist/benchmarks-BjXxjAke.js +0 -2824
- package/dist/benchmarks-BjXxjAke.js.map +0 -1
- package/dist/index-Bh9wLd0_.d.ts +0 -1097
- package/dist/index-Bh9wLd0_.d.ts.map +0 -1
- package/dist/index-DZeFm-BP.d.ts +0 -680
- package/dist/index-DZeFm-BP.d.ts.map +0 -1
- package/dist/inspect-C6c4zuKp.js.map +0 -1
- package/dist/memory-CUk1mgPY.js +0 -5778
- package/dist/memory-CUk1mgPY.js.map +0 -1
- package/dist/search-BBr5eUyT.js +0 -275
- package/dist/search-BBr5eUyT.js.map +0 -1
- package/dist/sources/index.d.ts +0 -376
- package/dist/sources/index.d.ts.map +0 -1
- package/dist/sources/index.js +0 -615
- package/dist/sources/index.js.map +0 -1
- package/dist/types-m2QB86fF.d.ts.map +0 -1
- package/docs/eval/rag-eval-roadmap.md +0 -123
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory-BH6oT1Qe.js","names":["canonicalJson","stripUndefined","mergeScopes","mergeScopes","isRecord","stringField","numberField","delay","stringField","numberField"],"sources":["../src/memory/holdout.ts","../src/memory/adapter.ts","../src/memory/rank.ts","../src/memory/branch.ts","../src/memory/graphiti.ts","../src/memory/json.ts","../src/memory/lifecycle.ts","../src/memory/schemas.ts","../src/memory/hindsight.ts","../src/memory/mem0.ts","../src/memory/neo4j.ts","../src/memory/tools.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\n\nimport { mulberry32 } from '@tangle-network/agent-eval'\n\nimport type { OffPolicyTrajectory } from '@tangle-network/agent-eval/rl'\n\nimport { sha256 } from '../ids'\n\nimport type {\n AgentMemoryHit,\n RetrievalHoldoutBypassReason,\n RetrievalHoldoutCallContext,\n RetrievalHoldoutConfig,\n RetrievalHoldoutEvent,\n RetrievalHoldoutResult,\n RetrievalHoldoutSessionState,\n} from './types'\n\nexport type {\n RetrievalHoldoutBypassReason,\n RetrievalHoldoutCallContext,\n RetrievalHoldoutConfig,\n RetrievalHoldoutEligibleItem,\n RetrievalHoldoutEvent,\n RetrievalHoldoutResult,\n RetrievalHoldoutSessionState,\n} from './types'\n\n/**\n * Deterministic uniform [0,1) for assignment draws. The sha256 key derivation is ours — it makes\n * every draw replayable from the logged keys alone (design rule D5) — while the generator core is\n * the substrate's `mulberry32` (@tangle-network/agent-eval statistics vocabulary), seeded with the\n * top 32 bits of the digest, so the statistical machinery is reused rather than forked.\n */\nexport function deterministicRng(key: string): number {\n return mulberry32(Number.parseInt(sha256(key).slice(0, 8), 16))()\n}\n\n// Deterministic serialization for hashing: keys sorted, undefined-valued entries stripped, so\n// the same logical scope/config always produces the same hash regardless of construction order.\n// Known limitation: NaN and Infinity serialize as null (JSON.stringify semantics) — acceptable\n// for hashing because it is deterministic; bigint has no JSON form at all, so it fails loud.\nfunction canonicalJson(value: unknown): string {\n if (typeof value === 'bigint') {\n throw new TypeError('canonicalJson: bigint values are not supported in holdout hashing')\n }\n if (value === undefined) return 'null'\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`)\n return `{${entries.join(',')}}`\n }\n return JSON.stringify(value)\n}\n\n/**\n * Value-hash of the knobs that DEFINE the experiment (epsilon + watchlist, order-independent).\n * Everything else on the config (callbacks, attribution stamps, privacy flags) does not change\n * which assignments are drawn, so it stays out of the hash.\n */\nexport function retrievalHoldoutConfigHash(\n config: Pick<RetrievalHoldoutConfig, 'epsilon' | 'watchlist'>,\n): string {\n return sha256(\n canonicalJson({ epsilon: config.epsilon, watchlist: [...(config.watchlist ?? [])].sort() }),\n ).slice(0, 16)\n}\n\n// Malformed knobs silently corrupt propensities (epsilon>1 forces holdout with dropPropensity>1;\n// epsilon<0 disables it while still logging a control-arm-shaped stream), so fail loud instead.\nfunction assertValidHoldoutConfig(config: RetrievalHoldoutConfig): void {\n const { epsilon, watchlist } = config\n if (typeof epsilon !== 'number' || !Number.isFinite(epsilon) || epsilon < 0 || epsilon > 1) {\n throw new Error(`retrieval holdout epsilon must be a number in [0, 1], got ${String(epsilon)}`)\n }\n if (\n watchlist !== undefined &&\n (!Array.isArray(watchlist) || watchlist.some((id) => typeof id !== 'string'))\n ) {\n throw new Error('retrieval holdout watchlist must be an array of item-id strings')\n }\n}\n\n// Observability must never break retrieval: a throwing onEvent sink is logged and swallowed,\n// deliberately identical on the randomized and bypass paths. The cost is a lost event — a hole\n// the analysis can see as a callIndex gap — never a lost or altered retrieval result.\nfunction safeEmit(config: RetrievalHoldoutConfig, event: RetrievalHoldoutEvent): void {\n try {\n config.onEvent(event)\n } catch (error) {\n console.error(\n '[agent-knowledge] retrieval holdout onEvent sink threw; retrieval continues',\n error,\n )\n }\n}\n\n/**\n * Pure per-call holdout: takes post-filter hits, returns delivered hits plus the log event\n * and the next session state. Suppression only removes items (no backfill), and it happens\n * before rendering so a drop session's context is byte-identical to a natural smaller retrieval.\n */\nexport function applyRetrievalHoldout(\n hits: AgentMemoryHit[],\n config: RetrievalHoldoutConfig,\n ctx: RetrievalHoldoutCallContext = {},\n): RetrievalHoldoutResult {\n assertValidHoldoutConfig(config)\n const rng = config.rng ?? deterministicRng\n const sessionId = ctx.sessionId ?? ctx.scope?.sessionId\n const holdoutEligible = typeof sessionId === 'string' && sessionId.length > 0\n const base = holdoutEventBase(hits, config, ctx)\n\n let session: RetrievalHoldoutSessionState | undefined\n if (holdoutEligible) {\n const prior = ctx.session?.sessionId === sessionId ? ctx.session : undefined\n session = prior ?? {\n sessionId,\n callCount: 0,\n // The epsilon coin depends only on sessionId, so assignment is independent of task\n // features by construction and exactly replayable (design rules D1 + D5).\n sessionHoldout: rng(`${sessionId}#holdout`) < config.epsilon,\n targetId: null,\n pickPropensity: null,\n }\n session = { ...session, callCount: session.callCount + 1 }\n }\n\n const watchlistEligible = base.watchlistEligible\n\n if (session?.sessionHoldout && session.targetId === null && watchlistEligible.length > 0) {\n // Draw once, uniformly over watchlist ∩ E at the first intersecting call, then stay sticky.\n // Candidates are sorted by id so the draw does not depend on retrieval ordering.\n const candidates = [...watchlistEligible].sort()\n const index = Math.min(\n Math.floor(rng(`${session.sessionId}#pick`) * candidates.length),\n candidates.length - 1,\n )\n const picked = candidates[index]\n if (picked !== undefined) {\n session = { ...session, targetId: picked, pickPropensity: 1 / candidates.length }\n }\n }\n\n const targetId = session?.sessionHoldout ? (session.targetId ?? null) : null\n const droppedId = targetId !== null && hits.some((hit) => hit.id === targetId) ? targetId : null\n const delivered = droppedId === null ? hits : hits.filter((hit) => hit.id !== droppedId)\n\n const pickPropensity = session?.sessionHoldout ? (session.pickPropensity ?? null) : null\n const event: RetrievalHoldoutEvent = {\n ...base,\n callIndex: session?.callCount ?? 0,\n holdoutEligible,\n sessionHoldout: session?.sessionHoldout ?? false,\n sessionTargetId: targetId,\n droppedId,\n pickPropensity,\n dropPropensity: pickPropensity !== null ? config.epsilon * pickPropensity : null,\n deliveredIds: delivered.map((hit) => hit.id),\n }\n safeEmit(config, event)\n\n return droppedId === null\n ? { delivered: hits, event, ...(session !== undefined ? { session } : {}) }\n : { delivered, event, ...(session !== undefined ? { session } : {}) }\n}\n\n/** Fields shared by randomized and bypass events: identity, attribution, config echo, eligibility. */\nfunction holdoutEventBase(\n hits: AgentMemoryHit[],\n config: RetrievalHoldoutConfig,\n ctx: Omit<RetrievalHoldoutCallContext, 'session'>,\n) {\n const sessionId = ctx.sessionId ?? ctx.scope?.sessionId\n const watchlist = config.watchlist ?? []\n const watchlistSet = new Set(watchlist)\n const plaintext = config.includePlaintextIdentifiers === true\n return {\n v: 1 as const,\n eventId: randomUUID(),\n ts: new Date().toISOString(),\n ...(config.adapterId !== undefined ? { adapterId: config.adapterId } : {}),\n ...(plaintext && sessionId !== undefined ? { sessionId } : {}),\n ...(ctx.taskId !== undefined ? { taskId: ctx.taskId } : {}),\n ...(sessionId !== undefined ? { sessionIdHash: sha256(sessionId).slice(0, 16) } : {}),\n ...(ctx.query !== undefined ? { queryHash: sha256(ctx.query).slice(0, 16) } : {}),\n ...(plaintext && ctx.scope !== undefined ? { scope: ctx.scope } : {}),\n ...(ctx.scope !== undefined\n ? { scopeHash: sha256(canonicalJson(ctx.scope)).slice(0, 16) }\n : {}),\n config: {\n epsilon: config.epsilon,\n watchlist: [...watchlist],\n ...(config.configVersion !== undefined ? { configVersion: config.configVersion } : {}),\n },\n configHash: retrievalHoldoutConfigHash(config),\n eligible: hits.map((hit, index) => ({\n id: hit.id,\n rank: index + 1,\n ...(typeof (hit.normalizedScore ?? hit.score) === 'number'\n ? { score: hit.normalizedScore ?? hit.score }\n : {}),\n kind: hit.kind,\n contentHash: sha256(hit.text).slice(0, 16),\n })),\n watchlistEligible: hits.filter((hit) => watchlistSet.has(hit.id)).map((hit) => hit.id),\n ...(config.corpusVersion !== undefined ? { corpusVersion: config.corpusVersion } : {}),\n }\n}\n\n/**\n * Logs a holdout event for adapter context paths that answer WITHOUT going through the\n * search→render seam (Neo4j short-term conversation context, raw-string getContext results),\n * so a consumer with a holdout configured still sees every call and the fraction-under-experiment\n * denominator stays honest instead of silently losing these calls. No suppression is applied:\n * dropping is only meaningful for retrieved memory hits, never for conversation context.\n */\nexport function emitRetrievalHoldoutBypass(\n hits: AgentMemoryHit[],\n config: RetrievalHoldoutConfig,\n ctx: Omit<RetrievalHoldoutCallContext, 'session'>,\n bypassReason: RetrievalHoldoutBypassReason,\n): RetrievalHoldoutEvent {\n assertValidHoldoutConfig(config)\n const event: RetrievalHoldoutEvent = {\n ...holdoutEventBase(hits, config, ctx),\n callIndex: 0,\n holdoutEligible: false,\n sessionHoldout: false,\n sessionTargetId: null,\n droppedId: null,\n pickPropensity: null,\n dropPropensity: null,\n deliveredIds: hits.map((hit) => hit.id),\n bypassReason,\n }\n safeEmit(config, event)\n return event\n}\n\n// Session states are tiny (5 scalar fields); the cap only guards unbounded long-lived processes.\n// Evicting a live session degrades detectably, not silently: a re-drawn target that differs\n// shows up in the log as a mixed-exposure session (same sessionIdHash, different sessionTargetId,\n// callIndex restarting at 1), which analysis excludes and counts.\nconst DEFAULT_MAX_TRACKED_SESSIONS = 10_000\n\n// Keyed by configHash VALUE, not config object identity: callers building options inline pass a\n// fresh config object per call (the natural adapter pattern), and identity-keying would silently\n// reset callIndex and re-draw the \"sticky\" target mid-session — one session logged as\n// under-treatment for two different items, invalidating the per-item estimate. The outer map is\n// bounded by the number of distinct experiment configs, in practice a handful.\nconst sessionRegistry = new Map<string, Map<string, RetrievalHoldoutSessionState>>()\n\n/**\n * Clears all sticky-session state. For test isolation and experiment-epoch boundaries;\n * sessions in flight afterwards re-draw deterministically (same rng keys), so with the default\n * rng a reset is invisible in the logs unless eligibility sets changed in between.\n */\nexport function resetRetrievalHoldoutRegistry(): void {\n sessionRegistry.clear()\n}\n\n/**\n * Convenience wrapper that threads session state internally, keyed by the VALUE of the\n * experiment-defining knobs (configHash = epsilon + sorted watchlist) plus sessionId, so a fresh\n * config object per call — the natural pattern when options are built inline — keeps full\n * stickiness. Distinct experiments never share session state; two config objects with the same\n * epsilon/watchlist are the same experiment by definition.\n */\nexport function applySessionStickyRetrievalHoldout(\n hits: AgentMemoryHit[],\n config: RetrievalHoldoutConfig,\n ctx: Omit<RetrievalHoldoutCallContext, 'session'> = {},\n): RetrievalHoldoutResult {\n assertValidHoldoutConfig(config)\n const sessionId = ctx.sessionId ?? ctx.scope?.sessionId\n const configHash = retrievalHoldoutConfigHash(config)\n let sessions = sessionRegistry.get(configHash)\n if (!sessions) {\n sessions = new Map()\n sessionRegistry.set(configHash, sessions)\n }\n const prior = sessionId !== undefined ? sessions.get(sessionId) : undefined\n const result = applyRetrievalHoldout(hits, config, {\n ...ctx,\n ...(prior ? { session: prior } : {}),\n })\n if (sessionId !== undefined && result.session) {\n const cap = config.maxTrackedSessions ?? DEFAULT_MAX_TRACKED_SESSIONS\n if (!sessions.has(sessionId) && sessions.size >= cap) {\n // Oldest-inserted-first: Map preserves insertion order and updates keep position.\n const oldest = sessions.keys().next().value\n if (oldest !== undefined) sessions.delete(oldest)\n }\n sessions.set(sessionId, result.session)\n }\n return result\n}\n\n/** Aggregated view of one session's holdout exposure — the randomization unit of this design. */\nexport interface RetrievalHoldoutSessionSummary {\n /** `${configHash}:${sessionIdHash}` — the trajectory's runId. */\n runId: string\n configHash: string\n sessionIdHash: string\n sessionHoldout: boolean\n sessionTargetId: string | null\n /** Item actually suppressed in this session (equals sessionTargetId when a drop occurred). */\n droppedId: string | null\n /** |watchlist ∩ E| at the session's first intersecting randomized call; 0 when never intersecting. */\n firstCandidateCount: number\n /** Randomized retrieval calls observed for this session. */\n callCount: number\n /** Adapter bypass calls observed for this session (logged, never randomized). */\n bypassCallCount: number\n /** Session-level probability of the OBSERVED assignment under the behavior policy. */\n behaviorProb: number\n /** True when the session's events disagree on arm or target (e.g. registry eviction re-draw). */\n mixedExposure: boolean\n /** Present only on sessions surfaced in `excluded` rather than converted. */\n exclusionReason?: 'mixed-exposure' | 'no-randomized-calls'\n}\n\nexport interface RetrievalHoldoutOffPolicyOptions {\n /**\n * Realized outcome PER SESSION, keyed by sessionIdHash — the session is the randomization\n * unit, so rewards are per session, never per call. A missing entry for an included session\n * throws: silently dropping unscored sessions would corrupt the estimator's denominator, so\n * filter events to scored sessions upstream instead.\n */\n rewards: Record<string, number>\n /**\n * Target-policy probability of the session's observed assignment. Default models the\n * always-deliver-in-full policy: 1 for full-delivery sessions, 0 for drop sessions.\n */\n targetProb?: (session: RetrievalHoldoutSessionSummary) => number\n /**\n * Reward-model prediction for the observed assignment. Supply this together\n * with `vHatTarget`; both estimates must come from evaluation data outside\n * this session.\n */\n qHatChosen?: (session: RetrievalHoldoutSessionSummary) => number | null\n /** Expected reward-model value under the target policy. */\n vHatTarget?: (session: RetrievalHoldoutSessionSummary) => number | null\n}\n\nexport interface RetrievalHoldoutOffPolicyResult {\n /** One trajectory per (configHash, sessionIdHash), never per call. */\n trajectories: OffPolicyTrajectory[]\n /** 1:1 with `trajectories` (same order): the diagnostic view of each converted session. */\n sessions: RetrievalHoldoutSessionSummary[]\n /** Sessions not converted because exposure was mixed or retrieval was bypassed. */\n excluded: RetrievalHoldoutSessionSummary[]\n /** Events with no sessionIdHash: outside session randomization, cannot join a reward. */\n unattributableEvents: number\n}\n\n/**\n * Maps retrieval-dropout events onto one `OffPolicyTrajectory` per session for use with\n * `inverseProbabilityWeighting`, `selfNormalizedImportanceWeighting`, or `doublyRobust`.\n * Randomization occurs once per session: the arm is selected with P(dropout) = epsilon and\n * the sticky target is drawn once,\n * uniformly over watchlist ∩ E at the session's first intersecting call.\n *\n * Session-level action space and behavior probabilities (they sum to 1 by construction):\n * - full delivery: `1 - epsilon`;\n * - drop candidate i of k = |watchlist ∩ E_first|: `epsilon / k` each (the draw event's logged\n * `dropPropensity`);\n * - sessions whose eligibility sets never intersect the watchlist: probability 1, because full\n * delivery was certain in either arm.\n *\n * Per-call events are repeated observations WITHIN one session-level randomization; per-call\n * IPW is statistically invalid for this design (per-call \"propensities\" imply an action\n * distribution summing to more than 1 and bias IPS downward). Calls where the sticky target is\n * absent from E, and adapter bypass calls, fold into the session summary (callCount /\n * bypassCallCount) instead of generating independent propensities.\n *\n * Join contract: `rewards` is keyed by `sessionIdHash` (sha256(sessionId) first 16 hex; compute\n * the same prefix over the outcome table's session ids, or log with\n * `includePlaintextIdentifiers: true` and join on raw ids upstream). Events are grouped per\n * (configHash, sessionIdHash) so different experiment configs are never pooled. Mixed-exposure\n * sessions (arm or target disagreement, e.g. after registry eviction) are excluded from the\n * trajectories and surfaced in `excluded` for analysis.\n */\nexport function toOffPolicyTrajectory(\n events: RetrievalHoldoutEvent[],\n options: RetrievalHoldoutOffPolicyOptions,\n): RetrievalHoldoutOffPolicyResult {\n if ((options.qHatChosen === undefined) !== (options.vHatTarget === undefined)) {\n throw new Error('qHatChosen and vHatTarget must be supplied together')\n }\n const groups = new Map<string, RetrievalHoldoutEvent[]>()\n let unattributableEvents = 0\n for (const event of events) {\n if (event.sessionIdHash === undefined) {\n unattributableEvents += 1\n continue\n }\n const key = `${event.configHash}:${event.sessionIdHash}`\n const group = groups.get(key)\n if (group) group.push(event)\n else groups.set(key, [event])\n }\n\n const trajectories: OffPolicyTrajectory[] = []\n const sessions: RetrievalHoldoutSessionSummary[] = []\n const excluded: RetrievalHoldoutSessionSummary[] = []\n\n for (const [runId, group] of groups) {\n const ordered = [...group].sort((a, b) => a.callIndex - b.callIndex || a.ts.localeCompare(b.ts))\n const randomized = ordered.filter((event) => event.holdoutEligible)\n const firstEvent = ordered[0]\n if (firstEvent?.sessionIdHash === undefined) continue\n const base = {\n runId,\n configHash: firstEvent.configHash,\n sessionIdHash: firstEvent.sessionIdHash,\n callCount: randomized.length,\n bypassCallCount: ordered.length - randomized.length,\n }\n const first = randomized[0]\n if (first === undefined) {\n excluded.push({\n ...base,\n sessionHoldout: false,\n sessionTargetId: null,\n droppedId: null,\n firstCandidateCount: 0,\n behaviorProb: 1,\n mixedExposure: false,\n exclusionReason: 'no-randomized-calls',\n })\n continue\n }\n\n const targets = new Set(\n randomized\n .map((event) => event.sessionTargetId)\n .filter((target): target is string => target !== null),\n )\n const arms = new Set(randomized.map((event) => event.sessionHoldout))\n const mixedExposure = targets.size > 1 || arms.size > 1\n const dropEvent = randomized.find((event) => event.droppedId !== null)\n const firstIntersecting = randomized.find((event) => event.watchlistEligible.length > 0)\n const sessionTargetId = dropEvent?.sessionTargetId ?? [...targets][0] ?? null\n\n let behaviorProb: number\n if (dropEvent !== undefined) {\n if (dropEvent.dropPropensity === null) {\n throw new Error(`holdout event ${dropEvent.eventId} recorded a drop without dropPropensity`)\n }\n // epsilon / |watchlist ∩ E_first|, logged at draw time.\n behaviorProb = dropEvent.dropPropensity\n } else if (!mixedExposure && sessionTargetId !== null) {\n // A drawn target implies its draw call dropped it, so a target with no drop event means\n // the batch is missing that session's calls. Weighting partial sessions biases the\n // estimate, so fail loud instead.\n throw new Error(\n `holdout session ${base.sessionIdHash} has a drawn target but no drop event: ` +\n 'the event batch is missing this session draw call',\n )\n } else if (firstIntersecting === undefined) {\n // No call could ever drop anything: full delivery was certain in either arm.\n behaviorProb = 1\n } else {\n // Control arm observed with a drop possible: the session-level assignment probability\n // is 1 − epsilon (NOT 1 − epsilon·pick, which is a per-item survival probability and\n // makes the implied action distribution sum past 1).\n behaviorProb = 1 - first.config.epsilon\n }\n\n const summary: RetrievalHoldoutSessionSummary = {\n ...base,\n sessionHoldout: first.sessionHoldout,\n sessionTargetId,\n droppedId: dropEvent?.droppedId ?? null,\n firstCandidateCount: firstIntersecting\n ? new Set(firstIntersecting.watchlistEligible).size\n : 0,\n behaviorProb,\n mixedExposure,\n ...(mixedExposure ? { exclusionReason: 'mixed-exposure' as const } : {}),\n }\n if (mixedExposure) {\n excluded.push(summary)\n continue\n }\n\n const reward = options.rewards[summary.sessionIdHash]\n if (reward === undefined) {\n throw new Error(\n `no reward for session ${summary.sessionIdHash}: ` +\n 'filter events to scored sessions before converting',\n )\n }\n const qHatChosen = options.qHatChosen?.(summary)\n const vHatTarget = options.vHatTarget?.(summary)\n trajectories.push({\n runId,\n reward,\n behaviorProb,\n targetProb: options.targetProb?.(summary) ?? (summary.droppedId === null ? 1 : 0),\n ...(options.qHatChosen === undefined ? {} : { qHatChosen: qHatChosen ?? null }),\n ...(options.vHatTarget === undefined ? {} : { vHatTarget: vHatTarget ?? null }),\n })\n sessions.push(summary)\n }\n\n return { trajectories, sessions, excluded, unattributableEvents }\n}\n","import { applySessionStickyRetrievalHoldout } from './holdout'\nimport { memoryHitToSourceRecord } from './source-record'\nimport type {\n AgentMemoryAdapter,\n AgentMemoryContext,\n AgentMemoryHit,\n AgentMemorySearchOptions,\n} from './types'\n\nexport async function defaultGetMemoryContext(\n adapter: Pick<AgentMemoryAdapter, 'search'>,\n query: string,\n options: AgentMemorySearchOptions = {},\n): Promise<AgentMemoryContext> {\n const hits = await adapter.search(query, options)\n // The holdout applies between search (eligibility set) and render (delivered set), and only\n // when explicitly configured: the unconfigured path must stay byte-identical, including\n // hit-array identity, so default behavior cannot drift.\n const delivered = options.holdout\n ? applySessionStickyRetrievalHoldout(hits, options.holdout, {\n query,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.scope?.tags?.taskId !== undefined ? { taskId: options.scope.tags.taskId } : {}),\n }).delivered\n : hits\n return {\n query,\n hits: delivered,\n sourceRecords: delivered.map((hit) => memoryHitToSourceRecord(hit, { scope: options.scope })),\n text: renderMemoryContext(delivered),\n }\n}\n\nexport function renderMemoryContext(hits: AgentMemoryHit[]): string {\n return hits\n .map((hit, index) => {\n const label = hit.title ?? `${hit.kind}:${hit.id}`\n const score =\n typeof hit.normalizedScore === 'number' ? ` score=${hit.normalizedScore.toFixed(3)}` : ''\n return [`[${index + 1}] ${label}${score}`, hit.text].join('\\n')\n })\n .join('\\n\\n')\n}\n","import type { AgentMemoryHit } from './types'\n\n/** Merges independently ranked memory lists without letting the first unscored list dominate. */\nexport function mergeRankedMemoryHits(\n groups: readonly (readonly AgentMemoryHit[])[],\n limit?: number,\n): AgentMemoryHit[] {\n const byIdentity = new Map<\n string,\n {\n hit: AgentMemoryHit\n score?: number\n reciprocalRank: number\n bestRank: number\n firstGroup: number\n encounter: number\n }\n >()\n let encounter = 0\n for (const [groupIndex, group] of groups.entries()) {\n for (const [rank, hit] of group.entries()) {\n const key = JSON.stringify([hit.uri, hit.text])\n const score = memoryHitScore(hit)\n const prior = byIdentity.get(key)\n if (!prior) {\n byIdentity.set(key, {\n hit,\n score,\n reciprocalRank: 1 / (60 + rank + 1),\n bestRank: rank,\n firstGroup: groupIndex,\n encounter,\n })\n } else {\n prior.reciprocalRank += 1 / (60 + rank + 1)\n prior.bestRank = Math.min(prior.bestRank, rank)\n if (score !== undefined && (prior.score === undefined || score > prior.score)) {\n prior.hit = hit\n prior.score = score\n }\n }\n encounter += 1\n }\n }\n return [...byIdentity.values()]\n .sort(\n (left, right) =>\n right.reciprocalRank - left.reciprocalRank ||\n Number(right.score !== undefined) - Number(left.score !== undefined) ||\n (right.score ?? 0) - (left.score ?? 0) ||\n left.bestRank - right.bestRank ||\n left.firstGroup - right.firstGroup ||\n left.encounter - right.encounter,\n )\n .map(({ hit }) => hit)\n .slice(0, limit ?? Number.POSITIVE_INFINITY)\n}\n\nfunction memoryHitScore(hit: AgentMemoryHit): number | undefined {\n const score = hit.normalizedScore ?? hit.score\n return score !== undefined && Number.isFinite(score) ? score : undefined\n}\n","import { canonicalJson } from '@tangle-network/agent-eval'\nimport { sha256, stableId } from '../ids'\nimport { defaultGetMemoryContext } from './adapter'\nimport { mergeRankedMemoryHits } from './rank'\nimport type {\n AgentMemoryAdapter,\n AgentMemoryScope,\n AgentMemoryWriteInput,\n AgentMemoryWriteResult,\n} from './types'\n\nexport type AgentMemoryVisibility = 'private' | 'team' | 'shared'\nexport type AgentMemoryBranchLifetime = 'resumable' | 'attempt'\n\nexport interface AgentMemorySharingPolicy {\n read: readonly AgentMemoryVisibility[]\n write: AgentMemoryVisibility\n}\n\nexport interface AgentMemoryJournalEntry {\n sequence: number\n input: AgentMemoryWriteInput\n result: AgentMemoryWriteResult\n}\n\nexport interface AgentMemoryBranchSnapshot {\n branchId: string\n lifetime: AgentMemoryBranchLifetime\n parentBranchId?: string\n adapterId: string\n policy: AgentMemorySharingPolicy\n baseScope: AgentMemoryScope\n journal: readonly AgentMemoryJournalEntry[]\n digest: `sha256:${string}`\n}\n\nexport interface AgentMemoryBranch extends AgentMemoryAdapter {\n readonly branchId: string\n readonly lifetime: AgentMemoryBranchLifetime\n readonly parentBranchId?: string\n readonly policy: AgentMemorySharingPolicy\n snapshot(): Promise<AgentMemoryBranchSnapshot>\n fork(options: {\n branchId: string\n adapter?: AgentMemoryAdapter\n policy?: AgentMemorySharingPolicy\n baseScope?: AgentMemoryScope\n lifetime?: AgentMemoryBranchLifetime\n }): Promise<AgentMemoryBranch>\n}\n\nexport interface CreateAgentMemoryBranchOptions {\n adapter: AgentMemoryAdapter\n branchId: string\n parentBranchId?: string\n policy?: AgentMemorySharingPolicy\n baseScope?: AgentMemoryScope\n /** Attempt branches use a new ID after a process restart and cannot bind persisted state. */\n lifetime?: AgentMemoryBranchLifetime\n /** Rebind a persisted branch whose external memory is still present. */\n snapshot?: AgentMemoryBranchSnapshot\n /** Optional exact logical scopes allowed to write, used by crash-safe experiments. */\n allowedWriteScopes?: readonly AgentMemoryScope[]\n}\n\nexport interface ForkAgentMemoryBranchSnapshotOptions {\n snapshot: AgentMemoryBranchSnapshot\n adapter: AgentMemoryAdapter\n branchId: string\n policy?: AgentMemorySharingPolicy\n baseScope?: AgentMemoryScope\n lifetime?: AgentMemoryBranchLifetime\n}\n\nconst DEFAULT_POLICY: AgentMemorySharingPolicy = {\n read: ['private'],\n write: 'private',\n}\n\ninterface AdapterLeaseState {\n references: number\n closed: boolean\n activeBranchIds: Set<string>\n closePromise?: Promise<void>\n}\n\nconst adapterLeases = new WeakMap<AgentMemoryAdapter, AdapterLeaseState>()\n\n/**\n * Isolates one candidate branch and records accepted writes for durable resume\n * or replay into a child branch, including a child backed by another provider.\n */\nexport function createAgentMemoryBranch(\n options: CreateAgentMemoryBranchOptions,\n): AgentMemoryBranch {\n if (typeof options.branchId !== 'string' || !options.branchId.trim()) {\n throw new Error('memory branchId must be a non-empty string')\n }\n const snapshot = options.snapshot\n if (snapshot && snapshot.branchId !== options.branchId) {\n throw new Error(\n `memory branch snapshot belongs to ${snapshot.branchId}, not ${options.branchId}`,\n )\n }\n if (snapshot && snapshot.adapterId !== options.adapter.id) {\n throw new Error(\n `memory branch snapshot uses ${snapshot.adapterId}, not ${options.adapter.id}; fork it to replay into another adapter`,\n )\n }\n if (snapshot?.lifetime === 'attempt') {\n throw new Error(\n 'memory branch attempt snapshots cannot be resumed; replay them into a fresh branch instead',\n )\n }\n if (options.lifetime !== undefined && !['resumable', 'attempt'].includes(options.lifetime)) {\n throw new Error('memory branch lifetime must be resumable or attempt')\n }\n if (snapshot) {\n assertDurableValue(snapshot, `${options.branchId}: branch snapshot`)\n assertSnapshotDigest(snapshot)\n }\n if (\n snapshot &&\n options.policy &&\n canonicalJson(stripUndefined(options.policy)) !== canonicalJson(stripUndefined(snapshot.policy))\n ) {\n throw new Error('memory branch snapshot policy cannot change during resume; fork it instead')\n }\n if (\n snapshot &&\n options.baseScope &&\n canonicalJson(stripUndefined(options.baseScope)) !==\n canonicalJson(stripUndefined(snapshot.baseScope))\n ) {\n throw new Error('memory branch snapshot scope cannot change during resume; fork it instead')\n }\n if (snapshot && options.lifetime && options.lifetime !== snapshot.lifetime) {\n throw new Error('memory branch snapshot lifetime cannot change during resume; fork it instead')\n }\n\n const branchId = options.branchId\n const parentBranchId = options.parentBranchId ?? snapshot?.parentBranchId\n const lifetime = options.lifetime ?? snapshot?.lifetime ?? 'resumable'\n const policy = normalizePolicy(options.policy ?? snapshot?.policy ?? DEFAULT_POLICY)\n assertBranchIsolation(options.adapter, branchId, policy, lifetime)\n const mergedBaseScope = mergeScopes(undefined, snapshot?.baseScope ?? options.baseScope)\n assertDurableValue(mergedBaseScope, `${branchId}: base scope`)\n const baseScope = cloneDurableValue(mergedBaseScope)\n const allowedWriteScopeKeys = options.allowedWriteScopes\n ? new Set(\n options.allowedWriteScopes.map((scope) =>\n canonicalJson(stripUndefined(mergeScopes(baseScope, scope))),\n ),\n )\n : undefined\n const journal = [...(snapshot?.journal ?? [])].map(cloneJournalEntry)\n let nextSequence = journal.reduce((max, entry) => Math.max(max, entry.sequence + 1), 0)\n const queues = new Map<string, Promise<void>>()\n const pending = new Set<Promise<unknown>>()\n const reads = new Set<Promise<unknown>>()\n const active = new Set<Promise<unknown>>()\n const touchedScopes = new Map<string, AgentMemoryScope>()\n for (const entry of journal) {\n const scope = mergeScopes(baseScope, entry.input.scope)\n touchedScopes.set(canonicalJson(stripUndefined(scope)), scope)\n }\n let mutationBarrier = Promise.resolve()\n const releaseAdapter = retainAdapter(options.adapter, branchId)\n let lifecycle: 'open' | 'closing' | 'closed' = 'open'\n let closePromise: Promise<void> | undefined\n\n const assertOpen = (operation: string): void => {\n if (lifecycle !== 'open') throw new Error(`${branchId}: cannot ${operation} a closed branch`)\n }\n const track = <T>(operation: Promise<T>): Promise<T> => {\n active.add(operation)\n void operation.then(\n () => active.delete(operation),\n () => active.delete(operation),\n )\n return operation\n }\n const trackRead = <T>(operation: Promise<T>): Promise<T> => {\n reads.add(operation)\n void operation.then(\n () => reads.delete(operation),\n () => reads.delete(operation),\n )\n return track(operation)\n }\n const flushWrites = async (): Promise<void> => {\n const results = await Promise.allSettled([...pending])\n const failures = results.flatMap((result) =>\n result.status === 'rejected' ? [result.reason] : [],\n )\n if (failures.length === 1) throw failures[0]\n if (failures.length > 1) {\n throw new AggregateError(failures, `${branchId}: pending memory writes failed`)\n }\n }\n const flushAll = async (): Promise<void> => {\n await flushWrites()\n await options.adapter.flush?.()\n }\n const runExclusive = async <T>(\n operation: () => Promise<T>,\n exclusiveOptions: { failOnOperationError?: boolean; flushAdapter?: boolean } = {},\n ): Promise<T> => {\n const precedingBarrier = mutationBarrier\n const precedingWrites = [...pending]\n const precedingReads = [...reads]\n let releaseBarrier!: () => void\n const ownBarrier = new Promise<void>((resolve) => {\n releaseBarrier = resolve\n })\n mutationBarrier = precedingBarrier.then(() => ownBarrier)\n await precedingBarrier\n const settled = await Promise.allSettled([...precedingWrites, ...precedingReads])\n const failures = settled.flatMap((result) =>\n result.status === 'rejected' ? [result.reason] : [],\n )\n try {\n if ((exclusiveOptions.failOnOperationError ?? true) && failures.length > 0) {\n if (failures.length === 1) throw failures[0]\n throw new AggregateError(failures, `${branchId}: pending memory operations failed`)\n }\n if (exclusiveOptions.flushAdapter ?? true) await options.adapter.flush?.()\n return await operation()\n } finally {\n releaseBarrier()\n }\n }\n\n const branch: AgentMemoryBranch = {\n id: `${options.adapter.id}:branch:${stableId('branch', branchId)}`,\n branchId,\n lifetime,\n ...(parentBranchId !== undefined ? { parentBranchId } : {}),\n policy,\n async search(query, searchOptions = {}) {\n assertOpen('search')\n const precedingBarrier = mutationBarrier\n return trackRead(\n (async () => {\n await precedingBarrier\n const logicalScope = mergeScopes(baseScope, searchOptions.scope)\n const scopes = policy.read.map((visibility) =>\n physicalScope(branchId, logicalScope, visibility),\n )\n const groups = await Promise.all(\n scopes.map(async (scope) => {\n const hits = await options.adapter.search(query, {\n ...searchOptions,\n scope,\n holdout: undefined,\n })\n return hits.map((hit) => ({\n ...hit,\n metadata: {\n ...hit.metadata,\n memoryBranchId: branchId,\n memoryVisibility: scope.tags?.memoryVisibility,\n },\n }))\n }),\n )\n return mergeRankedMemoryHits(groups, searchOptions.limit)\n })(),\n )\n },\n async getContext(query, searchOptions = {}) {\n assertOpen('read context from')\n return track(defaultGetMemoryContext(branch, query, searchOptions))\n },\n async write(input) {\n assertOpen('write to')\n const sequence = nextSequence\n nextSequence += 1\n assertDurableValue(input, `${branch.id}: write input`)\n const logicalInput = cloneWriteInput(input)\n logicalInput.id ??= stableId('memory_write', `${branchId}:${sequence}`)\n const logicalScope = mergeScopes(baseScope, logicalInput.scope)\n if (\n allowedWriteScopeKeys &&\n !allowedWriteScopeKeys.has(canonicalJson(stripUndefined(logicalScope)))\n ) {\n throw new Error(\n `${branch.id}: write scope was not declared in the experiment sequence cleanupScopes`,\n )\n }\n const scope = physicalScope(branchId, logicalScope, policy.write)\n const queueKey = writeQueueKey(branchId, logicalScope, policy.write)\n touchedScopes.set(canonicalJson(stripUndefined(logicalScope)), logicalScope)\n const previous = queues.get(queueKey) ?? Promise.resolve()\n const precedingBarrier = mutationBarrier\n let resultPromise: Promise<AgentMemoryWriteResult>\n const queued = Promise.all([previous.catch(() => undefined), precedingBarrier]).then(\n async () => {\n const result = await options.adapter.write({ ...logicalInput, scope })\n if (result.accepted) {\n assertDurableValue(result, `${branch.id}: write result`)\n journal.push({\n sequence,\n input: logicalInput,\n result: cloneWriteResult(result),\n })\n }\n return result\n },\n )\n resultPromise = queued\n const tail = queued.then(\n () => undefined,\n () => undefined,\n )\n queues.set(queueKey, tail)\n pending.add(resultPromise)\n void resultPromise.then(\n () => {\n pending.delete(resultPromise)\n if (queues.get(queueKey) === tail) queues.delete(queueKey)\n },\n () => {\n pending.delete(resultPromise)\n if (queues.get(queueKey) === tail) queues.delete(queueKey)\n },\n )\n return track(resultPromise)\n },\n async clear(scope) {\n assertOpen('clear')\n return track(\n runExclusive(\n async () => {\n if (!options.adapter.clear) {\n throw new Error(`${options.adapter.id}: adapter does not support scoped clear`)\n }\n const flushErrors: unknown[] = []\n try {\n await options.adapter.flush?.()\n } catch (error) {\n flushErrors.push(error)\n }\n const requestedScope = scope ? mergeScopes(baseScope, scope) : undefined\n const logicalScopes = new Map<string, AgentMemoryScope>()\n if (requestedScope) {\n logicalScopes.set(canonicalJson(stripUndefined(requestedScope)), requestedScope)\n for (const touched of touchedScopes.values()) {\n if (scopeMatches(touched, requestedScope)) {\n logicalScopes.set(canonicalJson(stripUndefined(touched)), touched)\n }\n }\n } else if (touchedScopes.size > 0) {\n for (const [key, touched] of touchedScopes) logicalScopes.set(key, touched)\n } else {\n logicalScopes.set(canonicalJson(stripUndefined(baseScope)), baseScope)\n }\n const visibilities = new Set([...policy.read, policy.write])\n const physicalScopes = new Map<string, AgentMemoryScope>()\n for (const logicalScope of logicalScopes.values()) {\n for (const visibility of visibilities) {\n const physical = physicalScope(branchId, logicalScope, visibility)\n physicalScopes.set(canonicalJson(stripUndefined(physical)), physical)\n }\n }\n const clearErrors: unknown[] = []\n const clearedPhysicalScopes = new Set<string>()\n for (const [key, physical] of physicalScopes) {\n try {\n await options.adapter.clear(physical)\n clearedPhysicalScopes.add(key)\n } catch (error) {\n clearErrors.push(error)\n }\n }\n if (clearedPhysicalScopes.size > 0) {\n for (let index = journal.length - 1; index >= 0; index -= 1) {\n const logical = mergeScopes(baseScope, journal[index]!.input.scope)\n const physical = physicalScope(branchId, logical, policy.write)\n if (clearedPhysicalScopes.has(canonicalJson(stripUndefined(physical)))) {\n journal.splice(index, 1)\n }\n }\n for (const [key, touched] of touchedScopes) {\n const physical = physicalScope(branchId, touched, policy.write)\n if (clearedPhysicalScopes.has(canonicalJson(stripUndefined(physical)))) {\n touchedScopes.delete(key)\n }\n }\n }\n const failures = [...flushErrors, ...clearErrors]\n if (failures.length === 1) throw failures[0]\n if (failures.length > 1) {\n throw new AggregateError(failures, `${branchId}: memory clear failed`)\n }\n },\n { failOnOperationError: false, flushAdapter: false },\n ),\n )\n },\n async flush() {\n assertOpen('flush')\n return track(runExclusive(async () => undefined))\n },\n close() {\n if (closePromise) return closePromise\n lifecycle = 'closing'\n closePromise = (async () => {\n const errors: unknown[] = []\n const operations = await Promise.allSettled([...active])\n for (const result of operations) {\n if (result.status === 'rejected') errors.push(result.reason)\n }\n try {\n await flushAll()\n } catch (error) {\n errors.push(error)\n }\n try {\n await releaseAdapter()\n } catch (error) {\n errors.push(error)\n }\n lifecycle = 'closed'\n if (errors.length === 1) throw errors[0]\n if (errors.length > 1) throw new AggregateError(errors, `${branch.id}: close failed`)\n })()\n return closePromise\n },\n async snapshot() {\n assertOpen('snapshot')\n return track(\n runExclusive(async () => {\n return createSnapshot({\n branchId,\n lifetime,\n adapterId: options.adapter.id,\n policy,\n baseScope,\n journal,\n ...(parentBranchId !== undefined ? { parentBranchId } : {}),\n })\n }),\n )\n },\n async fork(forkOptions) {\n assertOpen('fork')\n if (forkOptions.branchId === branchId) {\n throw new Error(`memory branch ${branchId}: child branchId must differ from its parent`)\n }\n return track(\n (async () =>\n forkAgentMemoryBranchSnapshot({\n snapshot: await branch.snapshot(),\n adapter: forkOptions.adapter ?? options.adapter,\n branchId: forkOptions.branchId,\n policy: forkOptions.policy,\n baseScope: forkOptions.baseScope,\n lifetime: forkOptions.lifetime,\n }))(),\n )\n },\n }\n return branch\n}\n\n/** Replays a durable journal into a fresh provider branch. */\nexport async function forkAgentMemoryBranchSnapshot(\n options: ForkAgentMemoryBranchSnapshotOptions,\n): Promise<AgentMemoryBranch> {\n assertDurableValue(options.snapshot, `${options.snapshot.branchId}: branch snapshot`)\n assertSnapshotDigest(options.snapshot)\n if (options.branchId === options.snapshot.branchId) {\n throw new Error(`memory branch ${options.branchId}: child branchId must differ from its parent`)\n }\n const child = createAgentMemoryBranch({\n adapter: options.adapter,\n branchId: options.branchId,\n parentBranchId: options.snapshot.branchId,\n policy: options.policy ?? options.snapshot.policy,\n baseScope: mergeScopes(options.snapshot.baseScope, options.baseScope),\n lifetime: options.lifetime ?? options.snapshot.lifetime,\n })\n try {\n for (const entry of options.snapshot.journal) {\n const result = await child.write(entry.input)\n if (!result.accepted) {\n throw new Error(\n `memory branch ${options.branchId}: adapter rejected replay of journal entry ${entry.sequence}`,\n )\n }\n }\n await child.flush?.()\n return child\n } catch (error) {\n const cleanupErrors: unknown[] = []\n try {\n await child.clear?.()\n } catch (cleanupError) {\n cleanupErrors.push(cleanupError)\n }\n try {\n await child.close?.()\n } catch (cleanupError) {\n cleanupErrors.push(cleanupError)\n }\n if (cleanupErrors.length > 0) {\n throw new AggregateError(\n [error, ...cleanupErrors],\n `memory branch ${options.branchId}: replay and cleanup failed`,\n )\n }\n throw error\n }\n}\n\nfunction assertBranchIsolation(\n adapter: AgentMemoryAdapter,\n branchId: string,\n policy: AgentMemorySharingPolicy,\n lifetime: AgentMemoryBranchLifetime,\n): void {\n const isolation = adapter.branchIsolation\n if (!isolation) {\n throw new Error(\n `${adapter.id}: cannot isolate memory branch '${branchId}': adapter must declare branchIsolation`,\n )\n }\n if (isolation.mode === 'unsupported') {\n throw new Error(\n `${adapter.id}: cannot isolate memory branch '${branchId}': ${isolation.reason}`,\n )\n }\n if (\n isolation.mode === 'scoped' &&\n isolation.processExitSafe === false &&\n lifetime !== 'attempt'\n ) {\n throw new Error(\n `${adapter.id}: memory branch '${branchId}' must use lifetime='attempt' because provider writes can outlive the worker process`,\n )\n }\n if (\n isolation.mode === 'scoped' &&\n isolation.processExitSafe === false &&\n (!Number.isSafeInteger(isolation.recoveryDelayMs) || isolation.recoveryDelayMs! <= 0)\n ) {\n throw new Error(`${adapter.id}: processExitSafe=false requires a positive recoveryDelayMs`)\n }\n if (isolation.mode === 'instance' && isolation.branchId !== branchId) {\n throw new Error(\n `${adapter.id}: adapter instance belongs to branch '${isolation.branchId}', not '${branchId}'`,\n )\n }\n if (\n isolation.mode === 'instance' &&\n isolation.supportsLogicalScopes !== true &&\n (policy.write !== 'shared' || policy.read.length !== 1 || policy.read[0] !== 'shared')\n ) {\n throw new Error(\n `${adapter.id}: dedicated branch instances without logical scope isolation support only shared memory policy`,\n )\n }\n}\n\nfunction retainAdapter(adapter: AgentMemoryAdapter, branchId: string): () => Promise<void> {\n const existing = adapterLeases.get(adapter)\n if (existing?.closed) throw new Error(`${adapter.id}: adapter is already closed`)\n const state = existing ?? { references: 0, closed: false, activeBranchIds: new Set<string>() }\n if (state.activeBranchIds.has(branchId)) {\n throw new Error(`${adapter.id}: memory branch '${branchId}' already has an open handle`)\n }\n state.activeBranchIds.add(branchId)\n state.references += 1\n adapterLeases.set(adapter, state)\n let released = false\n return async () => {\n if (released) return\n released = true\n state.activeBranchIds.delete(branchId)\n state.references -= 1\n if (state.references > 0) return\n if (!adapter.close) {\n adapterLeases.delete(adapter)\n return\n }\n state.closed = true\n state.closePromise ??= adapter.close()\n await state.closePromise\n }\n}\n\nfunction physicalScope(\n branchId: string,\n logical: AgentMemoryScope,\n visibility: AgentMemoryVisibility,\n): AgentMemoryScope {\n if (visibility === 'private' && !logical.agentId) {\n throw new Error('private memory requires scope.agentId')\n }\n if (visibility === 'team' && !logical.teamId) {\n throw new Error('team memory requires scope.teamId')\n }\n const principal =\n visibility === 'private' ? logical.agentId! : visibility === 'team' ? logical.teamId! : 'all'\n const namespace = [\n logical.namespace ?? 'default',\n stableId('branch', branchId),\n visibility,\n stableId('principal', principal),\n ].join('/')\n const physical: AgentMemoryScope = {\n ...logical,\n namespace,\n tags: {\n ...(logical.tags ?? {}),\n memoryBranchId: branchId,\n memoryVisibility: visibility,\n logicalNamespace: logical.namespace ?? 'default',\n },\n }\n if (visibility === 'shared') {\n delete physical.agentId\n delete physical.teamId\n } else if (visibility === 'team') {\n delete physical.agentId\n }\n return physical\n}\n\nfunction writeQueueKey(\n branchId: string,\n logical: AgentMemoryScope,\n visibility: AgentMemoryVisibility,\n): string {\n return canonicalJson(\n stripUndefined({\n branchId,\n visibility,\n tenantId: logical.tenantId,\n userId: logical.userId,\n agentId: logical.agentId,\n fallbackTeamId: logical.agentId === undefined ? logical.teamId : undefined,\n fallbackPrincipal:\n logical.agentId === undefined && logical.teamId === undefined ? 'unattributed' : undefined,\n }),\n )\n}\n\nfunction normalizePolicy(policy: AgentMemorySharingPolicy): AgentMemorySharingPolicy {\n const allowed = new Set<AgentMemoryVisibility>(['private', 'team', 'shared'])\n if (!allowed.has(policy.write) || policy.read.some((visibility) => !allowed.has(visibility))) {\n throw new Error('memory sharing policy contains an unsupported visibility')\n }\n const read = [...new Set(policy.read)]\n if (read.length === 0) throw new Error('memory sharing policy must read at least one visibility')\n return { read, write: policy.write }\n}\n\nfunction createSnapshot(\n input: Omit<AgentMemoryBranchSnapshot, 'digest'>,\n): AgentMemoryBranchSnapshot {\n const payload = cloneDurableValue({\n ...input,\n journal: [...input.journal].sort((a, b) => a.sequence - b.sequence),\n })\n assertDurableValue(payload, `${input.branchId}: branch snapshot`)\n return {\n ...payload,\n digest: `sha256:${sha256(canonicalJson(stripUndefined(payload)))}`,\n }\n}\n\nfunction assertSnapshotDigest(snapshot: AgentMemoryBranchSnapshot): void {\n const { digest, ...payload } = snapshot\n const actual = `sha256:${sha256(canonicalJson(stripUndefined(payload)))}`\n if (actual !== digest)\n throw new Error(`memory branch snapshot digest mismatch: ${digest} != ${actual}`)\n}\n\nfunction mergeScopes(base?: AgentMemoryScope, extra?: AgentMemoryScope): AgentMemoryScope {\n return {\n ...(base ?? {}),\n ...(extra ?? {}),\n tags: { ...(base?.tags ?? {}), ...(extra?.tags ?? {}) },\n }\n}\n\nfunction scopeMatches(actual: AgentMemoryScope, requested: AgentMemoryScope): boolean {\n for (const key of [\n 'tenantId',\n 'userId',\n 'agentId',\n 'teamId',\n 'runId',\n 'sessionId',\n 'namespace',\n ] as const) {\n if (requested[key] !== undefined && actual[key] !== requested[key]) return false\n }\n for (const [key, value] of Object.entries(requested.tags ?? {})) {\n if (actual.tags?.[key] !== value) return false\n }\n return true\n}\n\nfunction stripUndefined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stripUndefined)\n if (typeof value !== 'object' || value === null) return value\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, child]) => child !== undefined)\n .map(([key, child]) => [key, stripUndefined(child)]),\n )\n}\n\nfunction cloneWriteInput(input: AgentMemoryWriteInput): AgentMemoryWriteInput {\n return cloneDurableValue(input)\n}\n\nfunction cloneWriteResult(result: AgentMemoryWriteResult): AgentMemoryWriteResult {\n return cloneDurableValue(result)\n}\n\nfunction cloneJournalEntry(entry: AgentMemoryJournalEntry): AgentMemoryJournalEntry {\n return {\n sequence: entry.sequence,\n input: cloneWriteInput(entry.input),\n result: cloneWriteResult(entry.result),\n }\n}\n\nfunction assertDurableValue(value: unknown, label: string, seen = new WeakSet<object>()): void {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean' ||\n (typeof value === 'number' && Number.isFinite(value))\n ) {\n return\n }\n if (value === undefined) return\n if (typeof value !== 'object') {\n throw new Error(`${label} must contain only JSON-compatible values`)\n }\n if (seen.has(value)) throw new Error(`${label} must not contain cycles`)\n seen.add(value)\n if (Array.isArray(value)) {\n for (const child of value) {\n if (child === undefined) {\n throw new Error(`${label} arrays must not contain undefined values`)\n }\n assertDurableValue(child, label, seen)\n }\n } else {\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must contain only plain objects`)\n }\n for (const child of Object.values(value)) assertDurableValue(child, label, seen)\n }\n seen.delete(value)\n}\n\nfunction cloneDurableValue<T>(value: T): T {\n if (Array.isArray(value)) return value.map((child) => cloneDurableValue(child)) as T\n if (typeof value !== 'object' || value === null) return value\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [key, cloneDurableValue(child)]),\n ) as T\n}\n","import { randomUUID } from 'node:crypto'\nimport { canonicalJson } from '@tangle-network/agent-eval'\nimport { sha256, stableId } from '../ids'\nimport { defaultGetMemoryContext } from './adapter'\nimport { mergeRankedMemoryHits } from './rank'\nimport { memoryWriteResultToSourceRecord } from './source-record'\nimport type { AgentMemoryAdapter, AgentMemoryHit, AgentMemoryScope } from './types'\n\nexport interface GraphitiMcpClientLike {\n callTool(request: { name: string; arguments?: Record<string, unknown> }): Promise<unknown>\n}\n\nexport interface GraphitiMemoryAdapterOptions {\n client: GraphitiMcpClientLike\n id?: string\n /** Stable server/deployment identity for cache-key helpers. Never put credentials here. */\n backendRef?: string\n defaultScope?: AgentMemoryScope\n consistency?: 'queued' | 'visible'\n ingestionTimeoutMs?: number\n pollIntervalMs?: number\n /** Maximum episodes inspected to prove a queued write became visible. */\n episodeScanLimit?: number\n provenanceEpisodeLimit?: number\n search?: readonly ('facts' | 'nodes')[]\n toolNames?: Partial<GraphitiToolNames>\n}\n\nexport interface GraphitiToolNames {\n addMemory: string\n searchFacts: string\n searchNodes: string\n getEpisodes: string\n clearGraph: string\n}\n\ninterface GraphitiEpisode {\n uuid: string\n name?: string\n content?: string\n source_description?: string\n group_id?: string\n}\n\nconst DEFAULT_GRAPHITI_INGESTION_TIMEOUT_MS = 120_000\n\n/** Connects the official Graphiti MCP server without coupling to its Python internals. */\nexport function createGraphitiMemoryAdapter(\n options: GraphitiMemoryAdapterOptions,\n): AgentMemoryAdapter {\n assertGraphitiOptions(options)\n const id = options.id ?? 'graphiti'\n const consistency = options.consistency ?? 'visible'\n const tools = graphitiToolNames(options)\n const queued = new Map<string, { groupId: string; name: string }>()\n\n const adapter: AgentMemoryAdapter = {\n id,\n branchIsolation:\n consistency === 'visible'\n ? {\n mode: 'scoped',\n processExitSafe: false,\n recoveryDelayMs: options.ingestionTimeoutMs ?? DEFAULT_GRAPHITI_INGESTION_TIMEOUT_MS,\n }\n : {\n mode: 'unsupported',\n reason:\n 'queued Graphiti writes can become visible after a process restart; use consistency=\"visible\" for branch experiments',\n },\n async search(query, searchOptions = {}) {\n if (searchOptions.minScore !== undefined && !Number.isFinite(searchOptions.minScore)) {\n throw new Error(`${id}: minScore must be finite`)\n }\n const scope = mergeScopes(options.defaultScope, searchOptions.scope)\n const groupId = graphitiGroupId(id, scope)\n const modes = new Set(options.search ?? ['facts', 'nodes'])\n const kinds =\n searchOptions.kinds && searchOptions.kinds.length > 0 ? new Set(searchOptions.kinds) : null\n const searchFacts = modes.has('facts') && (!kinds || kinds.has('fact'))\n const searchNodes = modes.has('nodes') && (!kinds || kinds.has('entity'))\n const limit = searchOptions.limit ?? 10\n if (!Number.isSafeInteger(limit) || limit < 0) {\n throw new Error(`${id}: search limit must be a non-negative safe integer`)\n }\n if (limit === 0) return []\n const [factPayload, nodePayload] = await Promise.all([\n searchFacts\n ? callGraphiti(options.client, tools.searchFacts, {\n query,\n group_ids: [groupId],\n max_facts: limit,\n })\n : undefined,\n searchNodes\n ? callGraphiti(options.client, tools.searchNodes, {\n query,\n group_ids: [groupId],\n max_nodes: limit,\n ...(searchOptions.metadata?.entityTypes\n ? { entity_types: searchOptions.metadata.entityTypes }\n : {}),\n })\n : undefined,\n ])\n const hits = mergeRankedMemoryHits(\n [normalizeGraphitiFacts(factPayload, id), normalizeGraphitiNodes(nodePayload, id)].map(\n (group) =>\n group.filter((hit) => {\n if (searchOptions.minScore === undefined) return true\n const score = hit.normalizedScore ?? hit.score\n return score !== undefined && score >= searchOptions.minScore\n }),\n ),\n limit,\n )\n await enrichGraphitiProvenance(options, groupId, hits)\n return hits\n },\n async getContext(query, searchOptions = {}) {\n return defaultGetMemoryContext(adapter, query, searchOptions)\n },\n async write(input) {\n const scope = mergeScopes(options.defaultScope, input.scope)\n const groupId = graphitiGroupId(id, scope)\n const eventKey = canonicalJson(\n stripUndefined({\n id: input.id,\n kind: input.kind,\n text: input.text,\n title: input.title,\n role: input.role,\n metadata: input.metadata,\n }),\n )\n const episodeUuid =\n input.id === undefined ? randomUUID() : deterministicUuid(`${id}:${groupId}:${eventKey}`)\n const name = input.title ?? `${input.kind}:${input.id ?? stableId('event', eventKey)}`\n const sourceDescription = canonicalJson(\n stripUndefined({\n adapter: 'agent-knowledge',\n memoryKind: input.kind,\n eventId: input.id,\n actorId: input.metadata?.actorId,\n sessionId: scope.sessionId,\n role: input.role,\n scope,\n metadata: input.metadata ?? {},\n }),\n )\n await callGraphiti(options.client, tools.addMemory, {\n name,\n episode_body: input.text,\n group_id: groupId,\n source: input.kind === 'message' ? 'message' : 'text',\n source_description: sourceDescription,\n uuid: episodeUuid,\n ...(typeof input.metadata?.timestamp === 'string'\n ? { reference_time: input.metadata.timestamp }\n : {}),\n })\n queued.set(episodeUuid, { groupId, name })\n if (consistency === 'visible') {\n await waitForGraphitiEpisode(options, groupId, episodeUuid)\n queued.delete(episodeUuid)\n }\n const result = {\n accepted: true,\n id: episodeUuid,\n uri: `memory://${id}/${episodeUuid}`,\n kind: input.kind,\n metadata: {\n provider: 'graphiti',\n groupId,\n consistency,\n queued: consistency === 'queued',\n },\n } as const\n return {\n ...result,\n sourceRecord: memoryWriteResultToSourceRecord(result, input.text, { scope }),\n }\n },\n async clear(scope) {\n const groupId = graphitiGroupId(id, mergeScopes(options.defaultScope, scope))\n for (const [episodeUuid, pending] of queued) {\n if (pending.groupId !== groupId) continue\n await waitForGraphitiEpisode(options, groupId, episodeUuid)\n queued.delete(episodeUuid)\n }\n await callGraphiti(options.client, tools.clearGraph, { group_ids: [groupId] })\n },\n async flush() {\n for (const [episodeUuid, pending] of queued) {\n await waitForGraphitiEpisode(options, pending.groupId, episodeUuid)\n queued.delete(episodeUuid)\n }\n },\n }\n return adapter\n}\n\nasync function callGraphiti(\n client: GraphitiMcpClientLike,\n name: string,\n args: Record<string, unknown>,\n): Promise<unknown> {\n const raw = await client.callTool({ name, arguments: args })\n const payload = graphitiPayload(raw)\n if (isRecord(payload) && typeof payload.error === 'string') {\n throw new Error(`Graphiti ${name}: ${payload.error}`)\n }\n return payload\n}\n\nfunction graphitiPayload(raw: unknown): unknown {\n if (!isRecord(raw)) return raw\n if (raw.isError === true) throw new Error(`Graphiti MCP: ${toolText(raw) || 'tool call failed'}`)\n if (isRecord(raw.structuredContent)) return unwrapResult(raw.structuredContent)\n const text = toolText(raw)\n if (text) {\n try {\n return unwrapResult(JSON.parse(text))\n } catch {\n return { message: text }\n }\n }\n return unwrapResult(raw)\n}\n\nfunction unwrapResult(value: unknown): unknown {\n if (isRecord(value) && Object.keys(value).length === 1 && 'result' in value) {\n return value.result\n }\n return value\n}\n\nfunction toolText(raw: Record<string, unknown>): string {\n if (!Array.isArray(raw.content)) return ''\n return raw.content\n .filter(isRecord)\n .map((part) => (typeof part.text === 'string' ? part.text : ''))\n .filter(Boolean)\n .join('\\n')\n}\n\nfunction normalizeGraphitiFacts(raw: unknown, adapterId: string): AgentMemoryHit[] {\n const facts = isRecord(raw) && Array.isArray(raw.facts) ? raw.facts.filter(isRecord) : []\n return facts.flatMap((fact) => {\n const text = stringField(fact, ['fact', 'text'])\n if (!text) return []\n const factId =\n stringField(fact, ['uuid', 'id']) ??\n stableId('fact', canonicalJson(stripUndefined({ adapterId, text, fact })))\n const episodeUuids = stringArray(fact.episodes ?? fact.episode_uuids)\n const score = numberField(fact, ['score', 'relevance_score'])\n const normalizedScore = normalizedScoreOf(score)\n return [\n {\n id: factId,\n uri: `memory://${adapterId}/fact/${factId}`,\n kind: 'fact' as const,\n text,\n ...(stringField(fact, ['name']) ? { title: stringField(fact, ['name']) } : {}),\n ...(stringField(fact, ['created_at'])\n ? { createdAt: stringField(fact, ['created_at']) }\n : {}),\n ...(stringField(fact, ['invalid_at'])\n ? { validUntil: stringField(fact, ['invalid_at']) }\n : stringField(fact, ['expired_at'])\n ? { validUntil: stringField(fact, ['expired_at']) }\n : {}),\n ...(score !== undefined ? { score } : {}),\n ...(normalizedScore !== undefined ? { normalizedScore } : {}),\n metadata: {\n provider: 'graphiti',\n groupId: fact.group_id,\n sourceNodeUuid: fact.source_node_uuid,\n targetNodeUuid: fact.target_node_uuid,\n validAt: fact.valid_at,\n invalidAt: fact.invalid_at,\n episodeUuids,\n attributes: fact.attributes,\n },\n },\n ]\n })\n}\n\nfunction normalizeGraphitiNodes(raw: unknown, adapterId: string): AgentMemoryHit[] {\n const nodes = isRecord(raw) && Array.isArray(raw.nodes) ? raw.nodes.filter(isRecord) : []\n return nodes.flatMap((node) => {\n const name = stringField(node, ['name'])\n const summary = stringField(node, ['summary'])\n const text = summary ?? name\n if (!text) return []\n const nodeId =\n stringField(node, ['uuid', 'id']) ??\n stableId('node', canonicalJson(stripUndefined({ adapterId, text, node })))\n const score = numberField(node, ['score', 'relevance_score'])\n const normalizedScore = normalizedScoreOf(score)\n return [\n {\n id: nodeId,\n uri: `memory://${adapterId}/entity/${nodeId}`,\n kind: 'entity' as const,\n text,\n ...(name ? { title: name } : {}),\n ...(stringField(node, ['created_at'])\n ? { createdAt: stringField(node, ['created_at']) }\n : {}),\n ...(score !== undefined ? { score } : {}),\n ...(normalizedScore !== undefined ? { normalizedScore } : {}),\n metadata: {\n provider: 'graphiti',\n groupId: node.group_id,\n labels: node.labels,\n attributes: node.attributes,\n },\n },\n ]\n })\n}\n\nasync function enrichGraphitiProvenance(\n options: GraphitiMemoryAdapterOptions,\n groupId: string,\n hits: AgentMemoryHit[],\n): Promise<void> {\n const wanted = new Set(hits.flatMap((hit) => stringArray(hit.metadata?.episodeUuids)))\n if (wanted.size === 0) return\n const scan = await scanGraphitiEpisodes(\n options,\n groupId,\n wanted,\n options.provenanceEpisodeLimit ?? options.episodeScanLimit ?? 10_000,\n )\n const episodes = scan.episodes\n const byId = new Map(episodes.map((episode) => [episode.uuid, episode]))\n for (const hit of hits) {\n const episodeUuids = stringArray(hit.metadata?.episodeUuids)\n const sourceEpisodes = episodeUuids\n .map((uuid) => byId.get(uuid))\n .filter((episode): episode is GraphitiEpisode => episode !== undefined)\n const provenanceIncomplete = episodeUuids.some((uuid) => !byId.has(uuid))\n if (sourceEpisodes.length === 0) {\n if (provenanceIncomplete) {\n hit.metadata = { ...hit.metadata, provenanceIncomplete: true }\n }\n continue\n }\n const descriptions = sourceEpisodes\n .map((episode) => parseDescription(episode.source_description))\n .filter(isRecord)\n const first = descriptions[0]\n hit.metadata = {\n ...hit.metadata,\n sourceEpisodes,\n ...(provenanceIncomplete || !scan.complete ? { provenanceIncomplete: true } : {}),\n ...(first ?? {}),\n eventIds: uniqueStrings(descriptions.map((value) => value.eventId)),\n actorIds: uniqueStrings(descriptions.map((value) => value.actorId)),\n ...(typeof first?.eventId === 'string' ? { eventId: first.eventId } : {}),\n ...(typeof first?.actorId === 'string' ? { actorId: first.actorId } : {}),\n }\n }\n}\n\nasync function getGraphitiEpisodes(\n options: GraphitiMemoryAdapterOptions,\n groupId: string,\n limit: number,\n): Promise<GraphitiEpisode[]> {\n const raw = await callGraphiti(options.client, graphitiToolNames(options).getEpisodes, {\n group_ids: [groupId],\n max_episodes: limit,\n })\n if (!isRecord(raw) || !Array.isArray(raw.episodes)) return []\n return raw.episodes.filter(isRecord).flatMap((episode) => {\n const uuid = stringField(episode, ['uuid', 'id'])\n return uuid ? [{ ...episode, uuid } as GraphitiEpisode] : []\n })\n}\n\nasync function scanGraphitiEpisodes(\n options: GraphitiMemoryAdapterOptions,\n groupId: string,\n wanted: ReadonlySet<string>,\n maximum: number,\n): Promise<{ episodes: GraphitiEpisode[]; complete: boolean }> {\n let limit = Math.min(100, maximum)\n for (;;) {\n const episodes = await getGraphitiEpisodes(options, groupId, limit)\n const foundAll = [...wanted].every((uuid) => episodes.some((episode) => episode.uuid === uuid))\n if (foundAll || episodes.length < limit) return { episodes, complete: foundAll }\n if (limit === maximum) return { episodes, complete: false }\n limit = Math.min(maximum, limit * 2)\n }\n}\n\nasync function waitForGraphitiEpisode(\n options: GraphitiMemoryAdapterOptions,\n groupId: string,\n episodeUuid: string,\n): Promise<void> {\n const timeoutMs = options.ingestionTimeoutMs ?? DEFAULT_GRAPHITI_INGESTION_TIMEOUT_MS\n const pollIntervalMs = options.pollIntervalMs ?? 500\n const maximum = options.episodeScanLimit ?? 10_000\n const deadline = Date.now() + timeoutMs\n let scanLimitReached = false\n for (;;) {\n const scan = await scanGraphitiEpisodes(options, groupId, new Set([episodeUuid]), maximum)\n if (scan.complete) return\n scanLimitReached ||= scan.episodes.length >= maximum\n const remainingMs = deadline - Date.now()\n if (remainingMs <= 0) break\n await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, remainingMs)))\n }\n if (scanLimitReached) {\n throw new Error(\n `Graphiti episode ${episodeUuid} is outside episodeScanLimit=${maximum}; raise the limit or use a smaller group`,\n )\n }\n throw new Error(`Graphiti episode ${episodeUuid} was not visible after ${timeoutMs}ms`)\n}\n\nfunction graphitiGroupId(adapterId: string, scope: AgentMemoryScope): string {\n return `ak_${sha256(\n canonicalJson(\n stripUndefined({\n adapterId,\n tenantId: scope.tenantId,\n userId: scope.userId,\n agentId: scope.agentId,\n teamId: scope.teamId,\n runId: scope.runId,\n sessionId: scope.sessionId,\n namespace: scope.namespace,\n tags: scope.tags,\n }),\n ),\n ).slice(0, 32)}`\n}\n\nfunction graphitiToolNames(options: GraphitiMemoryAdapterOptions): GraphitiToolNames {\n return {\n addMemory: options.toolNames?.addMemory ?? 'add_memory',\n searchFacts: options.toolNames?.searchFacts ?? 'search_memory_facts',\n searchNodes: options.toolNames?.searchNodes ?? 'search_nodes',\n getEpisodes: options.toolNames?.getEpisodes ?? 'get_episodes',\n clearGraph: options.toolNames?.clearGraph ?? 'clear_graph',\n }\n}\n\nfunction assertGraphitiOptions(options: GraphitiMemoryAdapterOptions): void {\n if (options.id !== undefined && (typeof options.id !== 'string' || !options.id.trim())) {\n throw new Error('Graphiti id must be a non-empty string')\n }\n if (\n options.backendRef !== undefined &&\n (typeof options.backendRef !== 'string' || !options.backendRef.trim())\n ) {\n throw new Error('Graphiti backendRef must be a non-empty string')\n }\n if (options.consistency !== undefined && !['queued', 'visible'].includes(options.consistency)) {\n throw new Error('Graphiti consistency must be queued or visible')\n }\n for (const [name, value] of [\n ['ingestionTimeoutMs', options.ingestionTimeoutMs],\n ['pollIntervalMs', options.pollIntervalMs],\n ['episodeScanLimit', options.episodeScanLimit],\n ['provenanceEpisodeLimit', options.provenanceEpisodeLimit],\n ] as const) {\n if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {\n throw new Error(`Graphiti ${name} must be a positive safe integer`)\n }\n }\n for (const [name, value] of Object.entries(options.toolNames ?? {})) {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`Graphiti toolNames.${name} must be a non-empty string`)\n }\n }\n}\n\nfunction deterministicUuid(value: string): string {\n const hex = sha256(value)\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n}\n\nfunction parseDescription(value: string | undefined): unknown {\n if (!value) return undefined\n try {\n return JSON.parse(value)\n } catch {\n return undefined\n }\n}\n\nfunction mergeScopes(base?: AgentMemoryScope, extra?: AgentMemoryScope): AgentMemoryScope {\n return {\n ...(base ?? {}),\n ...(extra ?? {}),\n tags: { ...(base?.tags ?? {}), ...(extra?.tags ?? {}) },\n }\n}\n\nfunction uniqueStrings(values: unknown[]): string[] {\n return [...new Set(values.filter((value): value is string => typeof value === 'string'))]\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string')\n : []\n}\n\nfunction stringField(value: Record<string, unknown>, keys: readonly string[]): string | undefined {\n for (const key of keys) {\n const field = value[key]\n if (typeof field === 'string' && field.length > 0) return field\n }\n return undefined\n}\n\nfunction numberField(value: Record<string, unknown>, keys: readonly string[]): number | undefined {\n for (const key of keys) {\n const field = value[key]\n if (typeof field === 'number' && Number.isFinite(field)) return field\n }\n return undefined\n}\n\nfunction normalizedScoreOf(score: number | undefined): number | undefined {\n return score !== undefined && score >= 0 && score <= 1 ? score : undefined\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction stripUndefined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stripUndefined)\n if (!isRecord(value)) return value\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, child]) => child !== undefined)\n .map(([key, child]) => [key, stripUndefined(child)]),\n )\n}\n\nexport function graphitiMemoryAdapterIdentity(\n options: Pick<\n GraphitiMemoryAdapterOptions,\n | 'id'\n | 'consistency'\n | 'ingestionTimeoutMs'\n | 'pollIntervalMs'\n | 'episodeScanLimit'\n | 'provenanceEpisodeLimit'\n | 'search'\n | 'toolNames'\n | 'defaultScope'\n > & { backendRef: string },\n): string {\n if (typeof options.backendRef !== 'string' || !options.backendRef.trim()) {\n throw new Error('Graphiti backendRef must be a non-empty string')\n }\n return `sha256:${sha256(canonicalJson(stripUndefined(options)))}`\n}\n","import { canonicalJson } from '@tangle-network/agent-eval'\n\n/** Optional object properties are absent on the wire; other unsupported values still fail. */\nexport function canonicalMemoryJson(value: unknown): string {\n return canonicalJson(omitUndefinedProperties(value))\n}\n\nfunction omitUndefinedProperties(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(omitUndefinedProperties)\n if (\n value !== null &&\n typeof value === 'object' &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n ) {\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, child]) => child !== undefined)\n .map(([key, child]) => [key, omitUndefinedProperties(child)]),\n )\n }\n return value\n}\n","import type { AgentMemoryAdapter } from './types'\n\nexport const DEFAULT_MEMORY_CLEANUP_TIMEOUT_MS = 180_000\nexport const MEMORY_OPERATION_CANCELLATION_TIMEOUT_MS = 4_000\nexport const MEMORY_CAMPAIGN_DISPATCH_SHUTDOWN_TIMEOUT_MS = 5_000\n\nexport class AgentMemoryLifecycleTimeoutError extends Error {\n constructor(\n readonly operation: string,\n readonly timeoutMs: number,\n ) {\n super(`${operation} did not finish within ${timeoutMs}ms`)\n this.name = 'AgentMemoryLifecycleTimeoutError'\n }\n}\n\nexport class AgentMemoryLifecycleUnsafeError extends Error {\n constructor(\n readonly operation: string,\n readonly priorTimeout: AgentMemoryLifecycleTimeoutError,\n ) {\n super(\n `${operation} cannot start because '${priorTimeout.operation}' is still running after its ${priorTimeout.timeoutMs}ms timeout`,\n { cause: priorTimeout },\n )\n this.name = 'AgentMemoryLifecycleUnsafeError'\n }\n}\n\nconst timedOutResources = new WeakMap<object, AgentMemoryLifecycleTimeoutError>()\n\nexport function releaseMemoryAdapterCreatedAfterAbort(input: {\n creation: Promise<AgentMemoryAdapter | null>\n signal: AbortSignal\n dispose?: (adapter: AgentMemoryAdapter) => Promise<void>\n}): void {\n void input.creation.then(\n async (adapter) => {\n if (!adapter || !input.signal.aborted) return\n try {\n await adapter.close?.()\n } catch {}\n try {\n await input.dispose?.(adapter)\n } catch {}\n },\n () => undefined,\n )\n}\n\nexport async function createBoundedMemoryAdapter(input: {\n operation: string\n timeoutMs: number\n signal?: AbortSignal\n create(signal: AbortSignal): AgentMemoryAdapter | null | Promise<AgentMemoryAdapter | null>\n dispose?: (adapter: AgentMemoryAdapter) => Promise<void>\n}): Promise<AgentMemoryAdapter | null> {\n input.signal?.throwIfAborted()\n const abortController = new AbortController()\n const creation = Promise.resolve().then(() => input.create(abortController.signal))\n releaseMemoryAdapterCreatedAfterAbort({\n creation,\n signal: abortController.signal,\n dispose: input.dispose,\n })\n return runBoundedMemoryLifecycle({\n operation: input.operation,\n timeoutMs: input.timeoutMs,\n signal: input.signal,\n abortController,\n run: () => creation,\n })\n}\n\nexport function resolveMemoryCleanupTimeoutMs(value: number | undefined, label: string): number {\n const timeoutMs = value ?? DEFAULT_MEMORY_CLEANUP_TIMEOUT_MS\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new Error(`${label} cleanupTimeoutMs must be a positive safe integer`)\n }\n return timeoutMs\n}\n\nexport async function runBoundedMemoryLifecycle<T>(input: {\n operation: string\n timeoutMs: number\n /** Prevent later operations from using the same client while timed-out work may still be running. */\n resource?: object\n /** Cooperatively cancel provider work before reporting a timeout. */\n abortController?: AbortController\n /** Stop waiting when the owning operation is cancelled. */\n signal?: AbortSignal\n /** Let active work settle after cancellation before marking its resource unsafe. */\n cancellationTimeoutMs?: number\n run(): Promise<T> | T\n}): Promise<T> {\n input.signal?.throwIfAborted()\n if (\n input.cancellationTimeoutMs !== undefined &&\n (!Number.isSafeInteger(input.cancellationTimeoutMs) || input.cancellationTimeoutMs <= 0)\n ) {\n throw new Error(`${input.operation} cancellationTimeoutMs must be a positive safe integer`)\n }\n const priorTimeout = input.resource ? timedOutResources.get(input.resource) : undefined\n if (priorTimeout) throw new AgentMemoryLifecycleUnsafeError(input.operation, priorTimeout)\n let timeout: ReturnType<typeof setTimeout> | undefined\n let cancellationTimeout: ReturnType<typeof setTimeout> | undefined\n let timeoutError: AgentMemoryLifecycleTimeoutError | undefined\n let relayAbort: (() => void) | undefined\n const work = Promise.resolve().then(input.run)\n if (input.resource) {\n const resource = input.resource\n void work.then(\n () => {\n if (timeoutError && timedOutResources.get(resource) === timeoutError) {\n timedOutResources.delete(resource)\n }\n },\n () => {\n if (timeoutError && timedOutResources.get(resource) === timeoutError) {\n timedOutResources.delete(resource)\n }\n },\n )\n }\n const deadline = new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n timeoutError = new AgentMemoryLifecycleTimeoutError(input.operation, input.timeoutMs)\n if (input.resource) timedOutResources.set(input.resource, timeoutError)\n input.abortController?.abort(timeoutError)\n reject(timeoutError)\n }, input.timeoutMs)\n })\n const signal = input.signal\n const cancellation = signal\n ? new Promise<never>((_, reject) => {\n relayAbort = () => {\n const error = memoryLifecycleAbortError(input.operation)\n input.abortController?.abort(error)\n if (input.cancellationTimeoutMs === undefined) {\n reject(signal.reason ?? error)\n return\n }\n cancellationTimeout = setTimeout(() => {\n timeoutError = new AgentMemoryLifecycleTimeoutError(\n `${input.operation} cancellation`,\n input.cancellationTimeoutMs!,\n )\n if (input.resource) timedOutResources.set(input.resource, timeoutError)\n reject(timeoutError)\n }, input.cancellationTimeoutMs)\n }\n if (signal.aborted) relayAbort()\n else signal.addEventListener('abort', relayAbort, { once: true })\n })\n : undefined\n try {\n return await Promise.race([work, deadline, ...(cancellation ? [cancellation] : [])])\n } finally {\n if (timeout) clearTimeout(timeout)\n if (cancellationTimeout) clearTimeout(cancellationTimeout)\n if (relayAbort) signal?.removeEventListener('abort', relayAbort)\n }\n}\n\nfunction memoryLifecycleAbortError(operation: string): Error {\n const error = new Error(`${operation} aborted`)\n error.name = 'AbortError'\n return error\n}\n\nexport function memoryRecoveryDelayMs(adapter: AgentMemoryAdapter): number {\n const isolation = adapter.branchIsolation\n if (isolation?.mode !== 'scoped' || isolation.processExitSafe !== false) return 0\n const delayMs = isolation.recoveryDelayMs\n if (typeof delayMs !== 'number' || !Number.isSafeInteger(delayMs) || delayMs <= 0) {\n throw new Error(\n `${adapter.id}: processExitSafe=false requires a positive recoveryDelayMs for abandoned writes`,\n )\n }\n return delayMs\n}\n\nexport async function sleepForMemoryRecovery(\n delayMs: number,\n assertOwned: () => Promise<void>,\n timeoutMs = delayMs,\n operation = 'memory recovery visibility wait',\n signal?: AbortSignal,\n): Promise<void> {\n if (delayMs <= 0) return\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new Error(`${operation} timeout must be a positive safe integer`)\n }\n signal?.throwIfAborted()\n await waitForMemoryRecoveryDelay(Math.min(delayMs, timeoutMs), signal, operation)\n await assertOwned()\n if (delayMs > timeoutMs) throw new AgentMemoryLifecycleTimeoutError(operation, timeoutMs)\n}\n\nasync function waitForMemoryRecoveryDelay(\n delayMs: number,\n signal: AbortSignal | undefined,\n operation: string,\n): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n let timeout: ReturnType<typeof setTimeout> | undefined\n const abort = () => {\n if (timeout) clearTimeout(timeout)\n reject(signal?.reason ?? memoryLifecycleAbortError(operation))\n }\n timeout = setTimeout(() => {\n signal?.removeEventListener('abort', abort)\n resolve()\n }, delayMs)\n if (signal?.aborted) abort()\n else signal?.addEventListener('abort', abort, { once: true })\n })\n}\n\nexport function createMemoryExecutionPool(limit: number): {\n run<T>(operation: () => Promise<T>): Promise<T>\n} {\n let active = 0\n const waiters: Array<() => void> = []\n return {\n async run<T>(operation: () => Promise<T>): Promise<T> {\n if (active >= limit) await new Promise<void>((resolve) => waiters.push(resolve))\n active += 1\n try {\n return await operation()\n } finally {\n active -= 1\n waiters.shift()?.()\n }\n },\n }\n}\n","import { z } from 'zod'\n\nexport const AgentMemoryKindSchema = z.enum([\n 'message',\n 'entity',\n 'fact',\n 'preference',\n 'observation',\n 'reasoning-trace',\n])\n\nexport const AgentMemoryScopeSchema = z.object({\n tenantId: z.string().optional(),\n userId: z.string().optional(),\n agentId: z.string().optional(),\n teamId: z.string().optional(),\n runId: z.string().optional(),\n sessionId: z.string().optional(),\n namespace: z.string().optional(),\n tags: z.record(z.string(), z.string()).optional(),\n})\n\nexport const AgentMemoryHitSchema = z.object({\n id: z.string().min(1),\n uri: z.string().min(1),\n kind: AgentMemoryKindSchema,\n text: z.string().min(1),\n title: z.string().optional(),\n score: z.number().optional(),\n normalizedScore: z.number().optional(),\n confidence: z.number().optional(),\n createdAt: z.string().optional(),\n validUntil: z.string().optional(),\n lastVerifiedAt: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const AgentMemoryWriteInputSchema = z.object({\n kind: AgentMemoryKindSchema,\n text: z.string().min(1),\n id: z.string().optional(),\n title: z.string().optional(),\n role: z.enum(['system', 'user', 'assistant', 'tool']).optional(),\n entityName: z.string().optional(),\n entityType: z.string().optional(),\n category: z.string().optional(),\n predicate: z.string().optional(),\n subject: z.string().optional(),\n object: z.string().optional(),\n confidence: z.number().min(0).max(1).optional(),\n scope: AgentMemoryScopeSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n","import { setTimeout as delay } from 'node:timers/promises'\nimport { z } from 'zod'\nimport { sha256 } from '../ids'\nimport { defaultGetMemoryContext } from './adapter'\nimport { canonicalMemoryJson } from './json'\nimport { runBoundedMemoryLifecycle } from './lifecycle'\nimport { AgentMemoryWriteInputSchema } from './schemas'\nimport { memoryWriteResultToSourceRecord } from './source-record'\nimport type { AgentMemoryAdapter, AgentMemoryHit, AgentMemoryScope } from './types'\n\n/** Transport owns endpoint selection and authentication; paths are always bank-bound here. */\nexport interface HindsightClientLike {\n request(input: {\n method: 'GET' | 'POST'\n path: string\n body?: unknown\n signal: AbortSignal\n }): Promise<{ status: number; body: unknown }>\n}\n\nexport interface HindsightMemoryAdapterOptions {\n client: HindsightClientLike\n /** Stable deployment identity, never a credential. Changing it changes every bank identity. */\n backendRef: string\n branchId: string\n requestTimeoutMs?: number\n ingestionTimeoutMs?: number\n pollIntervalMs?: number\n maxTextChars?: number\n recallMaxTokens?: number\n}\n\nexport class HindsightOperationUnknownError extends Error {\n constructor(\n readonly bankId: string,\n readonly operationId: string,\n readonly documentId: string,\n options?: ErrorOptions,\n ) {\n super(\n 'Hindsight retain is unresolved; retry the same write id and bytes to reconcile it before checkpointing',\n options,\n )\n this.name = 'HindsightOperationUnknownError'\n }\n}\n\nconst operationSchema = z.object({\n operation_id: z.string(),\n status: z.enum(['pending', 'processing', 'completed', 'failed', 'cancelled', 'not_found']),\n})\nconst documentSchema = z.object({\n id: z.string(),\n bank_id: z.string(),\n original_text: z.string().nullable(),\n document_metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n})\nconst recallSchema = z.object({\n results: z.array(\n z.object({\n id: z.string().min(1),\n text: z.string(),\n type: z.string().nullable().optional(),\n document_id: z.string().nullable().optional(),\n chunk_id: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n source_fact_ids: z.array(z.string()).nullable().optional(),\n scores: z\n .object({ final: z.number().nullable().optional() })\n .passthrough()\n .nullable()\n .optional(),\n }),\n ),\n source_facts: z.record(z.string(), z.unknown()).nullable().optional(),\n source_facts_truncated: z.boolean().nullable().optional(),\n})\n\n/** Dedicated bank identity includes the entire logical scope, including the existing branch partition. */\nexport function hindsightMemoryBankId(input: {\n backendRef: string\n branchId: string\n scope: AgentMemoryScope\n}): string {\n if (!input.backendRef.trim() || !input.branchId.trim())\n throw new Error('Hindsight requires backendRef and branchId')\n if (!input.scope.namespace?.trim()) {\n throw new Error('Hindsight memory requires an explicit stable play scope.namespace')\n }\n if (input.scope.tags?.memoryBranchId !== input.branchId) {\n throw new Error('Hindsight memory scope must belong to its bound AgentMemoryBranch')\n }\n return `ak-${sha256(canonicalMemoryJson(input))}`\n}\n\n/** Hindsight 0.10.2 adapter. Snapshots remain accepted-input journals, never provider database snapshots. */\nexport function createHindsightMemoryAdapter(\n options: HindsightMemoryAdapterOptions,\n): AgentMemoryAdapter {\n if (!options.backendRef?.trim() || !options.branchId?.trim())\n throw new Error('Hindsight requires backendRef and branchId')\n const requestTimeoutMs = bounded(options.requestTimeoutMs ?? 15_000, 300_000, 'requestTimeoutMs')\n const ingestionTimeoutMs = bounded(\n options.ingestionTimeoutMs ?? 120_000,\n 600_000,\n 'ingestionTimeoutMs',\n )\n const pollIntervalMs = bounded(options.pollIntervalMs ?? 1_000, 30_000, 'pollIntervalMs')\n const maxTextChars = bounded(options.maxTextChars ?? 8_000, 100_000, 'maxTextChars')\n const maxTokens = bounded(options.recallMaxTokens ?? 1_000, 16_000, 'recallMaxTokens')\n const id = `hindsight-0.10.2:${sha256(options.backendRef)}`\n const unresolved = new Map<string, HindsightOperationUnknownError>()\n let version: Promise<void> | undefined\n\n async function request(\n method: 'GET' | 'POST',\n path: string,\n body?: unknown,\n timeoutMs = requestTimeoutMs,\n ) {\n const abortController = new AbortController()\n const response = await runBoundedMemoryLifecycle({\n operation: `Hindsight ${method} ${path}`,\n timeoutMs,\n resource: options.client,\n abortController,\n run: () =>\n options.client.request({\n method,\n path,\n ...(body === undefined ? {} : { body }),\n signal: abortController.signal,\n }),\n })\n if (response.status !== 404 && (response.status < 200 || response.status >= 300)) {\n throw new Error(`Hindsight ${method} failed with HTTP ${response.status}`)\n }\n return response\n }\n async function checkVersion() {\n version ??= (async () => {\n const response = await request('GET', '/version')\n const parsed = z.object({ api_version: z.literal('0.10.2') }).safeParse(response.body)\n if (response.status !== 200 || !parsed.success)\n throw new Error('Hindsight adapter requires the qualified 0.10.2 API')\n })()\n await version\n }\n function bank(scope: AgentMemoryScope | undefined) {\n return hindsightMemoryBankId({\n backendRef: options.backendRef,\n branchId: options.branchId,\n scope: scope ?? {},\n })\n }\n function path(bankId: string, suffix: string) {\n return `/v1/default/banks/${encodeURIComponent(bankId)}${suffix}`\n }\n async function readDocument(bankId: string, documentId: string) {\n const response = await request(\n 'GET',\n path(bankId, `/documents/${encodeURIComponent(documentId)}`),\n )\n return response.status === 404 ? null : documentSchema.parse(response.body)\n }\n async function readOperation(bankId: string, operationId: string, timeoutMs = requestTimeoutMs) {\n const response = await request(\n 'GET',\n path(bankId, `/operations/${operationId}`),\n undefined,\n timeoutMs,\n )\n if (response.status === 404) return { operation_id: operationId, status: 'not_found' as const }\n const operation = operationSchema.parse(response.body)\n if (operation.operation_id !== operationId)\n throw new Error('Hindsight returned another operation identity')\n return operation\n }\n\n const adapter: AgentMemoryAdapter = {\n id,\n // Late writes remain confined to this exact branch's dedicated banks. This is not a cancellation guarantee.\n branchIsolation: { mode: 'instance', branchId: options.branchId, supportsLogicalScopes: true },\n async search(query, searchOptions = {}) {\n const bankId = bank(searchOptions.scope)\n if (!query.trim()) throw new Error('Hindsight recall requires a nonempty query')\n const limit = searchOptions.limit ?? 10\n if (!Number.isSafeInteger(limit) || limit < 0 || limit > 100)\n throw new Error('Hindsight recall limit must be between 0 and 100')\n if (searchOptions.minScore !== undefined && !Number.isFinite(searchOptions.minScore))\n throw new Error('Hindsight minScore must be finite')\n if (limit === 0) return []\n await checkVersion()\n const response = await request('POST', path(bankId, '/memories/recall'), {\n query,\n budget: 'low',\n max_tokens: maxTokens,\n include: { entities: null, source_facts: { max_tokens: maxTokens } },\n })\n if (response.status === 404) return []\n const result = recallSchema.parse(response.body)\n const hits: AgentMemoryHit[] = result.results.map((hit) => ({\n id: hit.id,\n uri: `hindsight://${bankId}/memories/${encodeURIComponent(hit.id)}`,\n kind: hit.type === 'world' ? 'fact' : 'observation',\n text: hit.text,\n ...(hit.scores?.final == null ? {} : { score: hit.scores.final }),\n metadata: {\n provider: 'hindsight',\n backendRef: options.backendRef,\n bankId,\n branchId: options.branchId,\n providerFactType: hit.type ?? null,\n documentId: hit.document_id ?? null,\n chunkId: hit.chunk_id ?? null,\n provenance: hit.metadata ?? null,\n sourceFactIds: hit.source_fact_ids ?? [],\n sourceFacts: Object.fromEntries(\n (hit.source_fact_ids ?? []).flatMap((key) =>\n result.source_facts?.[key] === undefined ? [] : [[key, result.source_facts[key]]],\n ),\n ),\n sourceFactsTruncated: result.source_facts_truncated ?? null,\n evidenceStatus: 'provider-derived; source attribution is not independent validation',\n },\n }))\n return hits\n .filter(\n (hit) =>\n (!searchOptions.kinds?.length || searchOptions.kinds.includes(hit.kind)) &&\n (searchOptions.minScore === undefined ||\n (hit.score !== undefined && hit.score >= searchOptions.minScore)),\n )\n .slice(0, limit)\n },\n async getContext(query, searchOptions) {\n return defaultGetMemoryContext(adapter, query, searchOptions)\n },\n async write(raw) {\n const input = AgentMemoryWriteInputSchema.parse(raw)\n if (!input.id?.trim()) throw new Error('Hindsight writes require a stable caller id')\n if (input.text.length > maxTextChars)\n throw new Error(`Hindsight write exceeds ${maxTextChars} characters`)\n const bankId = bank(input.scope)\n const documentId = `ak-${sha256(input.id)}`\n const operationId = operationUuid(`${bankId}:${documentId}`)\n const identity = `${bankId}:${operationId}`\n const { scope, ...sourceInput } = input\n const inputDigest = sha256(canonicalMemoryJson(sourceInput))\n const expectedMetadata = {\n ak_input_sha256: inputDigest,\n ak_scope_sha256: sha256(canonicalMemoryJson(scope)),\n ak_source: canonicalMemoryJson(sourceInput),\n }\n const verifyDocument = (document: z.infer<typeof documentSchema> | null) => {\n if (\n !document ||\n document.id !== documentId ||\n document.bank_id !== bankId ||\n document.original_text !== input.text ||\n document.document_metadata?.ak_input_sha256 !== inputDigest ||\n document.document_metadata?.ak_scope_sha256 !== expectedMetadata.ak_scope_sha256\n ) {\n throw new Error('Hindsight document identity or bytes differ from this stable write id')\n }\n }\n await checkVersion()\n const prior = await readDocument(bankId, documentId)\n if (prior) verifyDocument(prior)\n let operation = await readOperation(bankId, operationId)\n // A retained source can outlive Hindsight's completed-operation retention window.\n if (prior && operation.status === 'not_found') {\n const unknown = new HindsightOperationUnknownError(bankId, operationId, documentId)\n unresolved.set(identity, unknown)\n throw unknown\n }\n const unknown = new HindsightOperationUnknownError(bankId, operationId, documentId)\n unresolved.set(identity, unknown)\n const deadline = Date.now() + ingestionTimeoutMs\n try {\n if (operation.status === 'not_found') {\n const submitted = await request('POST', path(bankId, '/memories'), {\n async: true,\n operation_id: operationId,\n items: [\n {\n content: input.text,\n document_id: documentId,\n metadata: expectedMetadata,\n tags: ['source:agent-knowledge'],\n observation_scopes: 'shared',\n context:\n 'Retained agent input. Claims of success or correctness remain attributed claims, not verified findings.',\n },\n ],\n })\n const acknowledgement = z\n .object({\n success: z.literal(true),\n bank_id: z.literal(bankId),\n async: z.literal(true),\n operation_id: z.literal(operationId),\n })\n .parse(submitted.body)\n if (!acknowledgement.success) throw new Error('Hindsight rejected retain')\n }\n while (operation.status !== 'completed') {\n const remaining = deadline - Date.now()\n if (remaining <= 0) throw unknown\n operation = await readOperation(\n bankId,\n operationId,\n Math.min(requestTimeoutMs, remaining),\n )\n if (operation.status === 'failed' || operation.status === 'cancelled') {\n throw new Error(\n `Hindsight retain is ${operation.status}; possible partial provider state requires inspection`,\n )\n }\n if (operation.status !== 'completed')\n await delay(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())))\n }\n verifyDocument(await readDocument(bankId, documentId))\n unresolved.delete(identity)\n return accepted('completed')\n } catch (cause) {\n throw new HindsightOperationUnknownError(bankId, operationId, documentId, { cause })\n }\n function accepted(operationStatus: string) {\n unresolved.delete(identity)\n const result = {\n accepted: true,\n id: input.id!,\n uri: `hindsight://${bankId}/documents/${documentId}`,\n kind: input.kind,\n metadata: {\n provider: 'hindsight',\n bankId,\n branchId: options.branchId,\n operationId,\n documentId,\n inputDigest,\n operationStatus,\n cost: 'unmeasured',\n },\n }\n return {\n ...result,\n sourceRecord: memoryWriteResultToSourceRecord(result, input.text, { scope }),\n }\n }\n },\n async flush() {\n if (unresolved.size) throw unresolved.values().next().value\n },\n }\n return adapter\n}\n\nfunction operationUuid(value: string): string {\n const hex = sha256(value)\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n}\n\nfunction bounded(value: number, max: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > max)\n throw new Error(`Hindsight ${name} must be an integer between 1 and ${max}`)\n return value\n}\n","import { randomUUID } from 'node:crypto'\nimport { canonicalJson } from '@tangle-network/agent-eval'\nimport { sha256, stableId } from '../ids'\nimport { defaultGetMemoryContext } from './adapter'\nimport { memoryWriteResultToSourceRecord } from './source-record'\nimport type {\n AgentMemoryAdapter,\n AgentMemoryHit,\n AgentMemoryKind,\n AgentMemoryScope,\n AgentMemorySearchOptions,\n AgentMemoryWriteInput,\n} from './types'\n\nexport type Mem0ClientMode = 'hosted' | 'oss'\n\ninterface Mem0Message {\n role: 'user' | 'assistant'\n content: string\n}\n\ninterface Mem0EntityOptions {\n userId?: string\n agentId?: string\n runId?: string\n}\n\ninterface Mem0SearchOptions {\n filters?: Record<string, unknown>\n topK?: number\n threshold?: number\n rerank?: boolean\n showExpired?: boolean\n}\n\nexport interface Mem0HostedClient {\n add: (\n messages: Mem0Message[],\n options: Mem0EntityOptions & {\n appId?: string\n metadata?: Record<string, unknown>\n infer?: boolean\n },\n ) => Promise<unknown>\n search: (query: string, options: Mem0SearchOptions & { latestOnly?: boolean }) => Promise<unknown>\n getAll?: (options: {\n filters?: Record<string, unknown>\n page?: number\n pageSize?: number\n latestOnly?: boolean\n showExpired?: boolean\n }) => Promise<unknown>\n delete?: (memoryId: string) => Promise<unknown>\n}\n\nexport interface Mem0OssClient {\n add: (\n messages: Mem0Message[],\n options: Mem0EntityOptions & {\n metadata?: Record<string, unknown>\n filters?: Record<string, unknown>\n infer?: boolean\n },\n ) => Promise<unknown>\n search: (query: string, options: Mem0SearchOptions) => Promise<unknown>\n getAll?: (options: {\n filters?: Record<string, unknown>\n topK?: number\n showExpired?: boolean\n }) => Promise<unknown>\n delete?: (memoryId: string) => Promise<unknown>\n}\n\ninterface Mem0MemoryAdapterBaseOptions {\n id?: string\n infer?: boolean\n rerank?: boolean\n /** Bounds delayed-delete visibility checks and abandoned hosted-write recovery waits. */\n ingestionTimeoutMs?: number\n pollIntervalMs?: number\n /** Stable deployment/account identity for cache-key helpers. Never put credentials here. */\n backendRef?: string\n defaultScope?: AgentMemoryScope\n}\n\nexport interface Mem0HostedMemoryAdapterOptions extends Mem0MemoryAdapterBaseOptions {\n client: Mem0HostedClient\n mode: 'hosted'\n appId?: string\n latestOnly?: boolean\n}\n\nexport interface Mem0OssMemoryAdapterOptions extends Mem0MemoryAdapterBaseOptions {\n client: Mem0OssClient\n mode: 'oss'\n appId?: never\n latestOnly?: never\n}\n\nexport type Mem0MemoryAdapterOptions = Mem0HostedMemoryAdapterOptions | Mem0OssMemoryAdapterOptions\n\ninterface Mem0PendingWriteProbe {\n text: string\n providerIds: Set<string>\n filters: Record<string, unknown>\n expiresAt: number\n}\n\n/** Connects both the hosted Mem0 client and the open-source `Memory` class. */\nexport function createMem0MemoryAdapter(options: Mem0MemoryAdapterOptions): AgentMemoryAdapter {\n assertMem0Options(options)\n const id = options.id ?? `mem0-${options.mode}`\n const pendingWrites = new Set<Mem0PendingWriteProbe>()\n\n const adapter: AgentMemoryAdapter = {\n id,\n branchIsolation:\n options.mode === 'oss'\n ? { mode: 'scoped' }\n : {\n mode: 'scoped',\n processExitSafe: false,\n recoveryDelayMs: options.ingestionTimeoutMs ?? 30_000,\n },\n async search(query, searchOptions = {}) {\n assertMem0SearchOptions(searchOptions, id)\n if (searchOptions.limit === 0) return []\n const scope = mergeScopes(options.defaultScope, searchOptions.scope)\n assertMem0ProviderScope(scope, options.mode, id, 'search')\n const requestedKinds = [...new Set(searchOptions.kinds ?? [])]\n const kindQueries = requestedKinds.length > 0 ? requestedKinds : [undefined]\n const payloads = await Promise.all(\n kindQueries.map((kind) =>\n options.client.search(query, {\n filters: mem0Filters(scope, options.appId, kind),\n topK: searchOptions.limit,\n threshold: searchOptions.minScore,\n ...(options.rerank !== undefined ? { rerank: options.rerank } : {}),\n ...(options.mode === 'hosted' && options.latestOnly !== undefined\n ? { latestOnly: options.latestOnly }\n : {}),\n }),\n ),\n )\n return mergeMem0Hits(\n payloads.flatMap((raw) => normalizeMem0Hits(raw, id, searchOptions)),\n searchOptions.limit,\n )\n },\n async getContext(query, searchOptions = {}) {\n return defaultGetMemoryContext(adapter, query, searchOptions)\n },\n async write(input) {\n const scope = mergeScopes(options.defaultScope, input.scope)\n assertMem0ProviderScope(scope, options.mode, id, 'write')\n pruneExpiredMem0PendingWrites(pendingWrites)\n const writeId = input.id ?? randomUUID()\n const writeFilters = mem0Filters(scope, options.appId)\n const pendingProbe: Mem0PendingWriteProbe = {\n text: input.text,\n providerIds: new Set(),\n filters: writeFilters,\n expiresAt: Number.POSITIVE_INFINITY,\n }\n pendingWrites.add(pendingProbe)\n const scopeMetadata = mem0ScopeMetadata(scope, options.appId)\n const metadata = compactRecord({\n ...input.metadata,\n agentKnowledgeWriteId: writeId,\n memoryKind: input.kind,\n memoryTitle: input.title,\n entityName: input.entityName,\n entityType: input.entityType,\n category: input.category,\n predicate: input.predicate,\n subject: input.subject,\n object: input.object,\n confidence: input.confidence,\n originalRole: input.role,\n ...scopeMetadata,\n })\n const entity = mem0Entity(scope, options.appId)\n let raw: unknown\n try {\n raw = await options.client.add([{ role: mem0Role(input.role), content: input.text }], {\n ...entity,\n metadata,\n infer: options.infer ?? true,\n ...(options.mode === 'oss' ? { filters: writeFilters } : {}),\n })\n } finally {\n pendingProbe.expiresAt = Date.now() + (options.ingestionTimeoutMs ?? 30_000)\n }\n if (options.mode === 'hosted' && !Array.isArray(raw)) {\n throw new Error(\n `${id}: hosted Mem0 add returned an unsupported response; mem0ai 3.x must return a memory array`,\n )\n }\n const items = extractMem0Items(raw)\n const mutations = items.filter((candidate) => mem0Event(candidate) !== 'NOOP')\n const durableMutations = mutations.filter((candidate) => mem0Event(candidate) !== 'DELETE')\n for (const candidate of durableMutations) {\n const providerId = stringField(candidate, ['id'])\n if (providerId) pendingProbe.providerIds.add(providerId)\n }\n if (durableMutations.length === 0) {\n pendingWrites.delete(pendingProbe)\n }\n const item = mutations[0] ?? items[0]\n const itemId = stringField(item, ['id']) ?? writeId\n const event = mem0Event(item)\n const events = [...new Set(mutations.map(mem0Event).filter(Boolean))]\n const result = {\n accepted: mutations.length > 0,\n id: itemId,\n uri: `memory://${id}/${encodeURIComponent(itemId)}`,\n kind: input.kind,\n metadata: {\n provider: 'mem0',\n mode: options.mode,\n ...(event ? { event } : {}),\n ...(events.length > 1 ? { events } : {}),\n },\n } as const\n return {\n ...result,\n sourceRecord: memoryWriteResultToSourceRecord(result, input.text, { scope }),\n }\n },\n async clear(scope) {\n const mergedScope = mergeScopes(options.defaultScope, scope)\n assertMem0ProviderScope(mergedScope, options.mode, id, 'clear')\n pruneExpiredMem0PendingWrites(pendingWrites)\n const clearFilters = mem0Filters(mergedScope, options.appId)\n if (Object.keys(clearFilters).length === 0) {\n throw new Error(`${id}: refusing an unscoped Mem0 clear`)\n }\n if (options.client.getAll && options.client.delete) {\n const pendingForClear = [...pendingWrites].filter((pending) =>\n mem0FiltersInclude(pending.filters, clearFilters),\n )\n const deletedIds = new Set<string>()\n const searchProbes = new Map<string, Set<string>>()\n const observedPending = new Set<Mem0PendingWriteProbe>()\n for (const pending of pendingForClear) {\n const ids = searchProbes.get(pending.text) ?? new Set<string>()\n for (const providerId of pending.providerIds) ids.add(providerId)\n searchProbes.set(pending.text, ids)\n if (pending.providerIds.size > 0) observedPending.add(pending)\n }\n for (const pending of pendingForClear) {\n for (const providerId of pending.providerIds) {\n if (deletedIds.has(providerId)) continue\n await options.client.delete(providerId)\n deletedIds.add(providerId)\n }\n }\n const visibilityTimeoutMs = options.ingestionTimeoutMs ?? 30_000\n const pollIntervalMs = options.pollIntervalMs ?? 250\n let visibilityDeadline = Date.now() + visibilityTimeoutMs\n for (let batch = 0; batch < 100; ) {\n const raw = await options.client.getAll(\n options.mode === 'hosted'\n ? {\n filters: mem0Filters(mergedScope, options.appId),\n page: 1,\n pageSize: 100,\n latestOnly: false,\n showExpired: true,\n }\n : {\n filters: mem0Filters(mergedScope, options.appId),\n topK: 100,\n showExpired: true,\n },\n )\n const items = extractMem0Items(raw)\n if (items.length === 0) {\n const searchableByQuery = await searchableMem0IdsForCleanup(\n options,\n clearFilters,\n searchProbes,\n )\n const searchableIds = new Set(\n [...searchableByQuery.values()].flatMap((ids) => [...ids]),\n )\n const unseenSearchIds = [...searchableIds].filter(\n (memoryId) => !deletedIds.has(memoryId),\n )\n for (const [query, ids] of searchableByQuery) {\n const known = searchProbes.get(query) ?? new Set<string>()\n for (const memoryId of ids) known.add(memoryId)\n searchProbes.set(query, known)\n if (ids.size > 0) {\n for (const pending of pendingForClear) {\n if (pending.text === query) observedPending.add(pending)\n }\n }\n }\n if (unseenSearchIds.length > 0) {\n for (const memoryId of unseenSearchIds) {\n await options.client.delete(memoryId)\n deletedIds.add(memoryId)\n }\n batch += 1\n visibilityDeadline = Date.now() + visibilityTimeoutMs\n continue\n }\n const unresolvedPending = pendingForClear.some(\n (pending) => !observedPending.has(pending),\n )\n const needsQuietWindow = pendingForClear.some(\n (pending) => pending.providerIds.size === 0,\n )\n const remainingMs = visibilityDeadline - Date.now()\n if (remainingMs <= 0) {\n if (!unresolvedPending && searchableIds.size === 0) {\n removeMem0PendingWrites(pendingWrites, pendingForClear)\n return\n }\n if (searchableIds.size > 0) {\n throw new Error(\n `${id}: deleted Mem0 memories remained searchable after ${visibilityTimeoutMs}ms`,\n )\n }\n throw new Error(\n `${id}: a Mem0 write never became visible for exact cleanup within ${visibilityTimeoutMs}ms`,\n )\n }\n if (!unresolvedPending && searchableIds.size === 0 && !needsQuietWindow) {\n removeMem0PendingWrites(pendingWrites, pendingForClear)\n return\n }\n await sleep(Math.min(pollIntervalMs, remainingMs))\n continue\n }\n const rawIds = items.map((item) => stringField(item, ['id']))\n if (!rawIds.every((memoryId): memoryId is string => memoryId !== undefined)) {\n throw new Error(`${id}: Mem0 returned memories without ids during scoped clear`)\n }\n const ids = [...new Set(rawIds)]\n for (const item of items) {\n const memoryId = stringField(item, ['id'])!\n const text =\n stringField(item, ['memory', 'text', 'content']) ??\n stringField(recordField(item, 'data'), ['memory', 'text', 'content'])\n if (!text) continue\n const idsForText = searchProbes.get(text) ?? new Set<string>()\n idsForText.add(memoryId)\n searchProbes.set(text, idsForText)\n for (const pending of pendingForClear) {\n if (pending.text === text || pending.providerIds.has(memoryId)) {\n observedPending.add(pending)\n }\n }\n }\n const unseenIds = ids.filter((memoryId) => !deletedIds.has(memoryId))\n if (unseenIds.length === 0) {\n const remainingMs = visibilityDeadline - Date.now()\n if (remainingMs <= 0) {\n throw new Error(\n `${id}: deleted Mem0 memories remained visible after ${visibilityTimeoutMs}ms`,\n )\n }\n await sleep(Math.min(pollIntervalMs, remainingMs))\n continue\n }\n for (const memoryId of unseenIds) {\n await options.client.delete(memoryId)\n deletedIds.add(memoryId)\n }\n batch += 1\n visibilityDeadline = Date.now() + visibilityTimeoutMs\n }\n throw new Error(\n `${id}: refused to clear more than ${deletedIds.size} Mem0 memories in one call`,\n )\n }\n throw new Error(`${id}: exact scoped clear requires Mem0 getAll plus per-memory delete`)\n },\n }\n return adapter\n}\n\nfunction assertMem0Options(options: Mem0MemoryAdapterOptions): void {\n if (options.id !== undefined && (typeof options.id !== 'string' || !options.id.trim())) {\n throw new Error('Mem0 id must be a non-empty string')\n }\n if (options.appId !== undefined && (typeof options.appId !== 'string' || !options.appId.trim())) {\n throw new Error('Mem0 appId must be a non-empty string')\n }\n if (\n options.backendRef !== undefined &&\n (typeof options.backendRef !== 'string' || !options.backendRef.trim())\n ) {\n throw new Error('Mem0 backendRef must be a non-empty string')\n }\n for (const [name, value] of [\n ['ingestionTimeoutMs', options.ingestionTimeoutMs],\n ['pollIntervalMs', options.pollIntervalMs],\n ] as const) {\n if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {\n throw new Error(`Mem0 ${name} must be a positive safe integer`)\n }\n }\n}\n\nfunction assertMem0SearchOptions(options: AgentMemorySearchOptions, adapterId: string): void {\n if (options.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 0)) {\n throw new Error(`${adapterId}: search limit must be a non-negative safe integer`)\n }\n if (options.minScore !== undefined && !Number.isFinite(options.minScore)) {\n throw new Error(`${adapterId}: minScore must be finite`)\n }\n}\n\nfunction assertMem0ProviderScope(\n scope: AgentMemoryScope,\n mode: Mem0ClientMode,\n adapterId: string,\n operation: 'search' | 'write' | 'clear',\n): void {\n if (scope.userId || scope.agentId || scope.runId || scope.namespace) return\n if (operation === 'clear') {\n throw new Error(\n `${adapterId}: refusing an unscoped Mem0 clear; provide scope.userId, scope.agentId, scope.runId, or scope.namespace`,\n )\n }\n throw new Error(\n `${adapterId}: Mem0 ${mode} ${operation} requires scope.userId, scope.agentId, scope.runId, or scope.namespace`,\n )\n}\n\nfunction normalizeMem0Hits(\n raw: unknown,\n adapterId: string,\n options: AgentMemorySearchOptions,\n): AgentMemoryHit[] {\n const limit = options.limit ?? Number.POSITIVE_INFINITY\n const kinds = options.kinds && options.kinds.length > 0 ? new Set(options.kinds) : null\n return extractMem0Items(raw)\n .map((item): AgentMemoryHit | undefined => {\n const text =\n stringField(item, ['memory', 'text', 'content']) ??\n stringField(recordField(item, 'data'), ['memory', 'text', 'content'])\n if (!text) return undefined\n const metadata = recordField(item, 'metadata')\n const kind = mem0Kind(metadata?.memoryKind ?? item?.memoryType)\n if (kinds && !kinds.has(kind)) return undefined\n const score = numberField(item, ['rerankScore', 'rerank_score', 'score'])\n if (options.minScore !== undefined && (score === undefined || score < options.minScore)) {\n return undefined\n }\n const memoryId =\n stringField(item, ['id']) ??\n stableId('mem', canonicalJson(compactRecord({ adapterId, text, metadata, item })))\n const normalizedScore = score !== undefined && score >= 0 && score <= 1 ? score : undefined\n return {\n id: memoryId,\n uri: `memory://${adapterId}/${encodeURIComponent(memoryId)}`,\n kind,\n text,\n ...(stringField(metadata, ['memoryTitle']) ? { title: String(metadata!.memoryTitle) } : {}),\n ...(score !== undefined ? { score } : {}),\n ...(normalizedScore !== undefined ? { normalizedScore } : {}),\n ...(dateField(item, ['createdAt', 'created_at'])\n ? { createdAt: dateField(item, ['createdAt', 'created_at']) }\n : {}),\n ...(dateField(item, ['expirationDate', 'expiration_date'])\n ? { validUntil: dateField(item, ['expirationDate', 'expiration_date']) }\n : {}),\n metadata: compactRecord({\n provider: 'mem0',\n ...metadata,\n categories: item?.categories,\n owner: item?.owner,\n runId: item?.runId,\n agentId: item?.agentId,\n userId: item?.userId,\n }),\n }\n })\n .filter((hit): hit is AgentMemoryHit => hit !== undefined)\n .slice(0, limit)\n}\n\nfunction mergeMem0Hits(hits: readonly AgentMemoryHit[], limit?: number): AgentMemoryHit[] {\n const unique = new Map<string, { hit: AgentMemoryHit; index: number; score?: number }>()\n for (const [index, hit] of hits.entries()) {\n const key = JSON.stringify([hit.uri, hit.text])\n const score = hit.normalizedScore ?? hit.score\n const finiteScore = score !== undefined && Number.isFinite(score) ? score : undefined\n const prior = unique.get(key)\n if (!prior) {\n unique.set(key, { hit, index, score: finiteScore })\n } else if (\n finiteScore !== undefined &&\n (prior.score === undefined || finiteScore > prior.score)\n ) {\n unique.set(key, { hit, index: prior.index, score: finiteScore })\n }\n }\n return [...unique.values()]\n .sort(\n (left, right) =>\n Number(right.score !== undefined) - Number(left.score !== undefined) ||\n (right.score ?? 0) - (left.score ?? 0) ||\n left.index - right.index,\n )\n .map(({ hit }) => hit)\n .slice(0, limit ?? Number.POSITIVE_INFINITY)\n}\n\nfunction extractMem0Items(raw: unknown): Array<Record<string, unknown>> {\n if (Array.isArray(raw)) return raw.filter(isRecord)\n if (!isRecord(raw)) return []\n for (const key of ['results', 'memories', 'data']) {\n if (Array.isArray(raw[key])) return raw[key].filter(isRecord)\n }\n return [raw]\n}\n\nfunction mem0Event(item: Record<string, unknown> | undefined): string | undefined {\n return (\n stringField(item, ['event']) ?? stringField(recordField(item, 'metadata'), ['event'])\n )?.toUpperCase()\n}\n\nfunction mem0Entity(scope: AgentMemoryScope, appId?: string): Record<string, string> {\n return compactStringRecord({\n userId: scope.userId,\n agentId: scope.agentId,\n appId,\n runId: scope.namespace ?? scope.runId,\n })\n}\n\nfunction mem0Filters(\n scope: AgentMemoryScope,\n appId: string | undefined,\n kind?: AgentMemoryKind,\n): Record<string, unknown> {\n const entity = mem0EntityFilters(scope, appId)\n const customMetadata = compactRecord({\n ...mem0CustomScopeMetadata(scope),\n memoryKind: kind,\n })\n return compactRecord({ ...entity, ...customMetadata })\n}\n\nfunction mem0ScopeMetadata(scope: AgentMemoryScope, appId?: string): Record<string, string> {\n return { ...mem0EntityFilters(scope, appId), ...mem0CustomScopeMetadata(scope) }\n}\n\nfunction mem0EntityFilters(scope: AgentMemoryScope, appId?: string): Record<string, string> {\n return compactStringRecord({\n user_id: scope.userId,\n agent_id: scope.agentId,\n run_id: scope.namespace ?? scope.runId,\n app_id: appId,\n })\n}\n\nfunction mem0CustomScopeMetadata(scope: AgentMemoryScope): Record<string, string> {\n const metadata = compactStringRecord({\n logical_run_id: scope.namespace ? scope.runId : undefined,\n tenant_id: scope.tenantId,\n team_id: scope.teamId,\n session_id: scope.sessionId,\n })\n for (const [key, value] of Object.entries(scope.tags ?? {})) {\n metadata[`tag_${key}`] = value\n }\n return metadata\n}\n\nasync function searchableMem0IdsForCleanup(\n options: Mem0MemoryAdapterOptions,\n filters: Record<string, unknown>,\n probes: ReadonlyMap<string, ReadonlySet<string>>,\n): Promise<ReadonlyMap<string, ReadonlySet<string>>> {\n const searchable = new Map<string, ReadonlySet<string>>()\n const entries = [...probes]\n for (let offset = 0; offset < entries.length; offset += 8) {\n const results = await Promise.all(\n entries.slice(offset, offset + 8).map(async ([query, expectedIds]) => {\n const raw = await options.client.search(query, {\n filters,\n topK: Math.min(100, Math.max(10, expectedIds.size)),\n ...(options.mode === 'hosted' ? { latestOnly: false, showExpired: true } : {}),\n })\n return extractMem0Items(raw).map((item) => {\n const memoryId = stringField(item, ['id'])\n if (!memoryId) {\n throw new Error(\n `${options.id ?? `mem0-${options.mode}`}: Mem0 search returned a memory without an id during clear verification`,\n )\n }\n return memoryId\n })\n }),\n )\n for (const [index, ids] of results.entries()) {\n const query = entries[offset + index]![0]\n searchable.set(query, new Set(ids))\n }\n }\n return searchable\n}\n\nfunction mem0FiltersInclude(\n candidate: Readonly<Record<string, unknown>>,\n requested: Readonly<Record<string, unknown>>,\n): boolean {\n return Object.entries(requested).every(([key, value]) => Object.is(candidate[key], value))\n}\n\nfunction removeMem0PendingWrites(\n pendingWrites: Set<Mem0PendingWriteProbe>,\n removed: readonly Mem0PendingWriteProbe[],\n): void {\n for (const pending of removed) pendingWrites.delete(pending)\n}\n\nfunction pruneExpiredMem0PendingWrites(pendingWrites: Set<Mem0PendingWriteProbe>): void {\n const now = Date.now()\n for (const pending of pendingWrites) {\n if (pending.expiresAt <= now) pendingWrites.delete(pending)\n }\n}\n\nfunction mem0Role(role: AgentMemoryWriteInput['role']): 'user' | 'assistant' {\n return role === 'assistant' || role === 'tool' ? 'assistant' : 'user'\n}\n\nfunction mem0Kind(value: unknown): AgentMemoryKind {\n switch (value) {\n case 'message':\n case 'entity':\n case 'fact':\n case 'preference':\n case 'observation':\n case 'reasoning-trace':\n return value\n default:\n return 'fact'\n }\n}\n\nfunction mergeScopes(base?: AgentMemoryScope, extra?: AgentMemoryScope): AgentMemoryScope {\n return {\n ...(base ?? {}),\n ...(extra ?? {}),\n tags: { ...(base?.tags ?? {}), ...(extra?.tags ?? {}) },\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction compactRecord(input: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined))\n}\n\nfunction compactStringRecord(input: Record<string, string | undefined>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(input).filter((entry): entry is [string, string] => entry[1] !== undefined),\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction recordField(\n value: Record<string, unknown> | undefined,\n key: string,\n): Record<string, unknown> | undefined {\n const field = value?.[key]\n return isRecord(field) ? field : undefined\n}\n\nfunction stringField(\n value: Record<string, unknown> | undefined,\n keys: readonly string[],\n): string | undefined {\n for (const key of keys) {\n const field = value?.[key]\n if (typeof field === 'string' && field.length > 0) return field\n }\n return undefined\n}\n\nfunction numberField(\n value: Record<string, unknown> | undefined,\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n const field = value?.[key]\n if (typeof field === 'number' && Number.isFinite(field)) return field\n }\n return undefined\n}\n\nfunction dateField(\n value: Record<string, unknown> | undefined,\n keys: readonly string[],\n): string | undefined {\n for (const key of keys) {\n const field = value?.[key]\n if (typeof field === 'string' && field.length > 0) return field\n if (field instanceof Date && !Number.isNaN(field.valueOf())) return field.toISOString()\n }\n return undefined\n}\n\n/** Stable identity useful for dispatch/cache keys without exposing client credentials. */\nexport function mem0MemoryAdapterIdentity(\n options: Pick<\n Mem0MemoryAdapterOptions,\n | 'mode'\n | 'id'\n | 'appId'\n | 'infer'\n | 'rerank'\n | 'latestOnly'\n | 'ingestionTimeoutMs'\n | 'pollIntervalMs'\n | 'defaultScope'\n > & { backendRef: string },\n): string {\n if (typeof options.backendRef !== 'string' || !options.backendRef.trim()) {\n throw new Error('Mem0 backendRef must be a non-empty string')\n }\n return `sha256:${sha256(canonicalJson(compactRecord(options)))}`\n}\n","import { canonicalJson } from '@tangle-network/agent-eval'\nimport { stableId } from '../ids'\nimport { defaultGetMemoryContext } from './adapter'\nimport { emitRetrievalHoldoutBypass } from './holdout'\nimport { mergeRankedMemoryHits } from './rank'\nimport { memoryHitToSourceRecord, memoryWriteResultToSourceRecord } from './source-record'\nimport type {\n AgentMemoryAdapter,\n AgentMemoryHit,\n AgentMemoryScope,\n AgentMemorySearchOptions,\n AgentMemoryWriteInput,\n AgentMemoryWriteResult,\n} from './types'\n\nexport interface Neo4jAgentMemoryAdapterOptions {\n client: object\n /** Match the transport passed to the official MemoryClient. */\n transport: 'rest' | 'bridge'\n /** Use Neo4j's whole-conversation context instead of query-based search. */\n contextMode?: 'search' | 'native'\n id?: string\n /** Assert that the client owns disposable external state for this exact branch. */\n branchId?: string\n}\n\nexport function createNeo4jAgentMemoryAdapter(\n options: Neo4jAgentMemoryAdapterOptions,\n): AgentMemoryAdapter {\n assertNeo4jOptions(options)\n const client = options.client as Record<string, unknown>\n const id = options.id ?? 'neo4j-agent-memory'\n const isolatedInstance = options.branchId !== undefined\n const adapter: AgentMemoryAdapter = {\n id,\n branchIsolation: options.branchId\n ? { mode: 'instance', branchId: options.branchId, supportsLogicalScopes: false }\n : {\n mode: 'unsupported',\n reason: 'create a separate MemoryClient namespace per branch and pass branchId',\n },\n async search(query, searchOptions = {}) {\n assertNeo4jSearchOptions(searchOptions, id)\n return searchNeo4jMemory(\n client,\n query,\n searchOptions,\n id,\n options.transport,\n isolatedInstance,\n )\n },\n async getContext(query, searchOptions = {}) {\n assertNeo4jSearchOptions(searchOptions, id)\n assertNeo4jSearchKinds(searchOptions.kinds, options.transport, id)\n const shortTerm = nested(client, ['shortTerm', 'short_term'], {})\n const sessionId = searchOptions.scope?.sessionId\n if (options.contextMode === 'native' && options.transport !== 'rest') {\n throw new Error(`${id}: Neo4j native context requires transport=\"rest\"`)\n }\n if (options.contextMode === 'native' && !sessionId) {\n throw new Error(`${id}: Neo4j native context requires scope.sessionId`)\n }\n if (\n options.contextMode === 'native' &&\n searchOptions.kinds?.some((kind) => kind !== 'message' && kind !== 'observation')\n ) {\n throw new Error(\n `${id}: Neo4j native context only returns message and observation memory kinds`,\n )\n }\n if (options.contextMode === 'native' && options.transport === 'rest' && sessionId) {\n assertNeo4jScopeSupported(\n searchOptions.scope,\n ['sessionId'],\n id,\n 'native context read',\n isolatedInstance,\n )\n const conversationContext = await callRequired(shortTerm, ['getContext'], [sessionId])\n const hits = normalizeConversationContextHits(conversationContext, searchOptions, id)\n const text = renderHits(hits)\n if (searchOptions.holdout) {\n emitRetrievalHoldoutBypass(\n hits,\n searchOptions.holdout,\n holdoutBypassContext(query, searchOptions),\n 'short-term-context',\n )\n }\n return {\n query,\n text,\n hits,\n sourceRecords: hits.map((hit) =>\n memoryHitToSourceRecord(hit, { scope: searchOptions.scope }),\n ),\n metadata: { adapter: id, rawContext: conversationContext },\n }\n }\n\n return defaultGetMemoryContext(adapter, query, searchOptions)\n },\n async write(input) {\n const result = await writeNeo4jMemory(client, input, id, options.transport, isolatedInstance)\n return {\n ...result,\n sourceRecord: memoryWriteResultToSourceRecord(result, input.text, { scope: input.scope }),\n }\n },\n async close() {\n await callOptional(client, ['close'], [])\n },\n }\n return adapter\n}\n\nfunction assertNeo4jOptions(options: Neo4jAgentMemoryAdapterOptions): void {\n if (typeof options.client !== 'object' || options.client === null) {\n throw new Error('Neo4j agent-memory client must be an object')\n }\n if (options.id !== undefined && (typeof options.id !== 'string' || !options.id.trim())) {\n throw new Error('Neo4j agent-memory id must be a non-empty string')\n }\n if (\n options.branchId !== undefined &&\n (typeof options.branchId !== 'string' || !options.branchId.trim())\n ) {\n throw new Error('Neo4j agent-memory branchId must be a non-empty string')\n }\n if (options.contextMode !== undefined && !['search', 'native'].includes(options.contextMode)) {\n throw new Error('Neo4j agent-memory contextMode must be search or native')\n }\n}\n\nfunction assertNeo4jSearchOptions(options: AgentMemorySearchOptions, adapterId: string): void {\n if (options.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 0)) {\n throw new Error(`${adapterId}: search limit must be a non-negative safe integer`)\n }\n if (options.minScore !== undefined && !Number.isFinite(options.minScore)) {\n throw new Error(`${adapterId}: minScore must be finite`)\n }\n}\n\nfunction assertNeo4jSearchKinds(\n kinds: AgentMemorySearchOptions['kinds'],\n transport: 'rest' | 'bridge',\n adapterId: string,\n): void {\n if (!kinds?.length) return\n const supported = new Set<AgentMemoryHit['kind']>(\n transport === 'rest'\n ? ['message', 'observation', 'entity']\n : ['message', 'observation', 'entity', 'preference', 'reasoning-trace'],\n )\n const unsupported = [...new Set(kinds.filter((kind) => !supported.has(kind)))]\n if (unsupported.length > 0) {\n throw new Error(\n `${adapterId}: Neo4j ${transport} cannot search memory kinds: ${unsupported.join(', ')}`,\n )\n }\n}\n\nfunction assertNeo4jBridgeCapability(\n transport: 'rest' | 'bridge',\n kind: AgentMemoryWriteInput['kind'],\n adapterId: string,\n): void {\n if (transport === 'bridge') return\n throw new Error(\n `${adapterId}: Neo4j REST cannot write ${kind}; use transport=\"bridge\" or map it to an entity/message`,\n )\n}\n\nasync function writeNeo4jMemory(\n client: Record<string, unknown>,\n input: AgentMemoryWriteInput,\n adapterId: string,\n transport: 'rest' | 'bridge',\n isolatedInstance: boolean,\n): Promise<AgentMemoryWriteResult> {\n const scope = input.scope ?? {}\n const sessionId = scope.sessionId ?? input.metadata?.sessionId\n assertNeo4jScopeSupported(\n input.scope,\n input.kind === 'message' || input.kind === 'observation'\n ? ['sessionId']\n : input.kind === 'reasoning-trace'\n ? ['sessionId', 'runId']\n : [],\n adapterId,\n `${input.kind} write`,\n isolatedInstance,\n )\n if (\n !isolatedInstance &&\n input.kind === 'reasoning-trace' &&\n scope.sessionId !== undefined &&\n scope.runId !== undefined\n ) {\n throw new Error(\n `${adapterId}: Neo4j reasoning write cannot enforce both sessionId and runId; provide one`,\n )\n }\n let result: unknown\n if (input.kind === 'message' || input.kind === 'observation') {\n if (transport === 'rest' && typeof sessionId !== 'string') {\n throw new Error(\n `${adapterId}: Neo4j REST message writes require scope.sessionId as the conversation id`,\n )\n }\n const shortTerm = nested(client, ['shortTerm', 'short_term'], client)\n const metadata = { ...input.metadata, agentKnowledgeKind: input.kind }\n result = await callRequired(\n shortTerm,\n ['addMessage'],\n [\n sessionId,\n neo4jMessageRole(input.role),\n input.text,\n { metadata, conversationId: sessionId },\n ],\n )\n } else if (input.kind === 'entity') {\n const longTerm = nested(client, ['longTerm', 'long_term'], client)\n result = await callRequired(\n longTerm,\n ['addEntity'],\n [\n input.entityName ?? input.title ?? input.text,\n input.entityType ?? 'custom',\n neo4jEntityOptions(input),\n ],\n )\n } else if (input.kind === 'preference') {\n assertNeo4jBridgeCapability(transport, input.kind, adapterId)\n const longTerm = nested(client, ['longTerm', 'long_term'], client)\n result = await callRequired(\n longTerm,\n ['addPreference'],\n [input.category ?? 'general', input.text, neo4jPreferenceOptions(input)],\n )\n } else if (input.kind === 'reasoning-trace') {\n const reasoning = nested(client, ['reasoning'], client)\n const conversationId = sessionId ?? scope.runId\n if (transport === 'rest') {\n if (typeof conversationId !== 'string') {\n throw new Error(\n `${adapterId}: Neo4j REST reasoning writes require scope.sessionId or scope.runId`,\n )\n }\n result = await callRequired(\n reasoning,\n ['recordStep'],\n [\n {\n conversationId,\n reasoning: input.text,\n actionTaken: stringMetadata(input.metadata, 'action') ?? input.title ?? 'memory',\n result:\n stringMetadata(input.metadata, 'result') ??\n stringMetadata(input.metadata, 'observation') ??\n stringMetadata(input.metadata, 'outcome'),\n },\n ],\n )\n } else {\n const trace = await callRequired(\n reasoning,\n ['startTrace'],\n [\n conversationId ?? stableId('session', input.text),\n stringMetadata(input.metadata, 'task') ?? input.title ?? input.text,\n ],\n )\n assertNeo4jWriteSucceeded(trace, adapterId, 'startTrace')\n const traceId = idFromResult(trace)\n if (!traceId) throw new Error(`${adapterId}: Neo4j startTrace returned no trace id`)\n try {\n const step = await callRequired(\n reasoning,\n ['addStep'],\n [\n traceId,\n {\n thought: input.text,\n observation: stringMetadata(input.metadata, 'observation'),\n action: stringMetadata(input.metadata, 'action'),\n },\n ],\n )\n assertNeo4jWriteSucceeded(step, adapterId, 'addStep')\n } catch (error) {\n try {\n await callRequired(\n reasoning,\n ['completeTrace'],\n [traceId, { outcome: 'agent-knowledge addStep failed', success: false }],\n )\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n `${adapterId}: Neo4j reasoning step and trace cleanup failed`,\n )\n }\n throw error\n }\n result = await callRequired(\n reasoning,\n ['completeTrace'],\n [\n traceId,\n {\n outcome: stringMetadata(input.metadata, 'outcome'),\n success:\n typeof input.metadata?.success === 'boolean' ? input.metadata.success : undefined,\n },\n ],\n )\n }\n } else {\n assertNeo4jBridgeCapability(transport, input.kind, adapterId)\n result = await callRequired(\n nested(client, ['longTerm', 'long_term'], client),\n ['addFact'],\n [\n input.subject ?? input.title ?? input.kind,\n input.predicate ?? 'states',\n input.object ?? input.text,\n ],\n )\n }\n\n assertNeo4jWriteSucceeded(result, adapterId, input.kind)\n\n const id =\n idFromResult(result) ??\n input.id ??\n stableId(\n 'mem',\n canonicalJson({ adapterId, kind: input.kind, text: input.text, scope: input.scope ?? {} }),\n )\n return {\n accepted: true,\n id,\n uri: `memory://${adapterId}/${encodeURIComponent(id)}`,\n kind: input.kind,\n metadata: { provider: 'neo4j-agent-memory', transport },\n }\n}\n\nfunction assertNeo4jWriteSucceeded(value: unknown, adapterId: string, operation: string): void {\n const response = record(value)\n if (!response) return\n const status = stringField(response, ['status'])?.toLowerCase()\n if (\n response.success === false ||\n response.ok === false ||\n response.isError === true ||\n status === 'failed' ||\n status === 'error'\n ) {\n const nestedError = record(response.error)\n const detail =\n stringField(response, ['error', 'message', 'detail']) ??\n (nestedError ? stringField(nestedError, ['message', 'detail']) : undefined)\n throw new Error(`${adapterId}: Neo4j ${operation} failed${detail ? `: ${detail}` : ''}`)\n }\n}\n\nasync function searchNeo4jMemory(\n client: Record<string, unknown>,\n query: string,\n options: AgentMemorySearchOptions,\n adapterId: string,\n transport: 'rest' | 'bridge',\n isolatedInstance: boolean,\n): Promise<AgentMemoryHit[]> {\n const limit = options.limit ?? 10\n if (limit === 0) return []\n assertNeo4jSearchKinds(options.kinds, transport, adapterId)\n const onlyConversationKinds =\n options.kinds !== undefined &&\n options.kinds.length > 0 &&\n options.kinds.every((kind) => kind === 'message' || kind === 'observation')\n assertNeo4jScopeSupported(\n options.scope,\n onlyConversationKinds ? ['sessionId'] : [],\n adapterId,\n 'search',\n isolatedInstance,\n )\n const searches: Promise<AgentMemoryHit[]>[] = []\n const kinds = options.kinds\n const includeKind = (kind: AgentMemoryHit['kind']) => !kinds?.length || kinds.includes(kind)\n const shortTerm = nested(client, ['shortTerm', 'short_term'], {})\n const longTerm = nested(client, ['longTerm', 'long_term'], {})\n const reasoning = nested(client, ['reasoning'], {})\n const wantsMessages = includeKind('message') || includeKind('observation')\n const hasConversation = typeof options.scope?.sessionId === 'string'\n\n if (\n transport === 'rest' &&\n wantsMessages &&\n !hasConversation &&\n options.kinds?.some((kind) => kind === 'message' || kind === 'observation')\n ) {\n throw new Error(\n `${adapterId}: Neo4j REST message search requires scope.sessionId as the conversation id`,\n )\n }\n\n if (wantsMessages && (transport === 'bridge' || hasConversation)) {\n const messageKinds = options.kinds?.filter(\n (kind) => kind === 'message' || kind === 'observation',\n ) ?? ['message', 'observation']\n searches.push(\n callRequired(shortTerm, ['searchMessages'], [query, searchMessagesOptions(options)]).then(\n (result) => normalizeHits(result, { ...options, kinds: messageKinds }, adapterId),\n ),\n )\n }\n\n if (includeKind('entity')) {\n searches.push(\n callRequired(longTerm, ['searchEntities'], [query, searchEntitiesOptions(options)]).then(\n (result) => normalizeHits(result, { ...options, kinds: ['entity'] }, adapterId),\n ),\n )\n }\n\n if (transport === 'bridge' && includeKind('preference')) {\n searches.push(\n callRequired(\n longTerm,\n ['searchPreferences'],\n [query, searchPreferencesOptions(options)],\n ).then((result) => normalizeHits(result, { ...options, kinds: ['preference'] }, adapterId)),\n )\n }\n\n if (transport === 'bridge' && includeKind('reasoning-trace')) {\n searches.push(\n callRequired(reasoning, ['getSimilarTraces'], [query, similarTracesOptions(options)]).then(\n (result) => normalizeHits(result, { ...options, kinds: ['reasoning-trace'] }, adapterId),\n ),\n )\n }\n\n return mergeRankedMemoryHits(await Promise.all(searches), limit)\n}\n\n// Mirrors defaultGetMemoryContext's holdout call context so bypass events join the same log stream.\nfunction holdoutBypassContext(\n query: string,\n options: AgentMemorySearchOptions,\n): { query: string; scope?: AgentMemoryScope; taskId?: string } {\n return {\n query,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.scope?.tags?.taskId !== undefined ? { taskId: options.scope.tags.taskId } : {}),\n }\n}\n\nfunction searchMessagesOptions(options: AgentMemorySearchOptions): Record<string, unknown> {\n return {\n limit: options.limit,\n sessionId: options.scope?.sessionId,\n conversationId: options.scope?.sessionId,\n threshold: options.minScore,\n }\n}\n\nfunction searchEntitiesOptions(options: AgentMemorySearchOptions): Record<string, unknown> {\n return {\n limit: options.limit,\n type: options.metadata?.type,\n }\n}\n\nfunction searchPreferencesOptions(options: AgentMemorySearchOptions): Record<string, unknown> {\n return {\n limit: options.limit,\n category: options.metadata?.category,\n }\n}\n\nfunction similarTracesOptions(options: AgentMemorySearchOptions): Record<string, unknown> {\n return {\n limit: options.limit,\n successOnly: options.metadata?.successOnly,\n }\n}\n\nfunction assertNeo4jScopeSupported(\n scope: AgentMemoryScope | undefined,\n allowedKeys: readonly (keyof AgentMemoryScope)[],\n adapterId: string,\n operation: string,\n isolatedInstance: boolean,\n): void {\n if (isolatedInstance || !scope) return\n const allowed = new Set<keyof AgentMemoryScope>(allowedKeys)\n const scopeKeys: readonly (keyof AgentMemoryScope)[] = [\n 'tenantId',\n 'userId',\n 'agentId',\n 'teamId',\n 'runId',\n 'sessionId',\n 'namespace',\n ]\n const supplied = scopeKeys.filter((key) => scope[key] !== undefined)\n if (scope.tags && Object.keys(scope.tags).length > 0) supplied.push('tags')\n const unsupported = supplied.filter((key) => !allowed.has(key))\n if (unsupported.length === 0) return\n throw new Error(\n `${adapterId}: Neo4j ${operation} cannot enforce scope fields: ${unsupported.join(', ')}; create a dedicated client and pass branchId`,\n )\n}\n\nfunction neo4jEntityOptions(input: AgentMemoryWriteInput): Record<string, unknown> {\n return {\n description: input.metadata?.description ?? input.title,\n }\n}\n\nfunction neo4jPreferenceOptions(input: AgentMemoryWriteInput): Record<string, unknown> {\n return {\n context: input.metadata?.context ?? input.title,\n }\n}\n\nasync function callOptional(\n target: Record<string, unknown>,\n names: string[],\n args: unknown[],\n): Promise<unknown> {\n for (const name of names) {\n const fn = target[name]\n if (typeof fn === 'function') return await fn.apply(target, args)\n }\n return undefined\n}\n\nasync function callRequired(\n target: Record<string, unknown>,\n names: string[],\n args: unknown[],\n): Promise<unknown> {\n for (const name of names) {\n const fn = target[name]\n if (typeof fn === 'function') return await fn.apply(target, args)\n }\n throw new Error(`Neo4j agent-memory client is missing method ${names.join(' or ')}`)\n}\n\nfunction nested(\n target: Record<string, unknown>,\n names: string[],\n fallback: Record<string, unknown>,\n): Record<string, unknown> {\n for (const name of names) {\n const value = target[name]\n if (value && typeof value === 'object') return value as Record<string, unknown>\n }\n return fallback\n}\n\nfunction normalizeHits(\n value: unknown,\n options: AgentMemorySearchOptions,\n adapterId: string,\n): AgentMemoryHit[] {\n const rawHits = rawHitsFrom(value)\n return rawHits\n .map((hit, index) => normalizeHit(hit, index, adapterId))\n .filter((hit): hit is AgentMemoryHit => hit !== null)\n .filter((hit) =>\n options.minScore === undefined\n ? true\n : (hit.normalizedScore ?? hit.score ?? 0) >= options.minScore!,\n )\n .filter((hit) => (options.kinds?.length ? options.kinds.includes(hit.kind) : true))\n .slice(0, options.limit ?? 10)\n}\n\nfunction normalizeHit(value: unknown, index: number, adapterId: string): AgentMemoryHit | null {\n if (typeof value === 'string') {\n return {\n id: stableId('mem', value),\n uri: `memory://${adapterId}/${stableId('mem', value)}`,\n kind: 'fact',\n text: value,\n normalizedScore: index === 0 ? 1 : undefined,\n }\n }\n const obj = record(value)\n if (!obj) return null\n const metadata = record(obj.metadata) ?? {}\n const kind = memoryKind(\n stringField(metadata, ['agentKnowledgeKind']) ?? stringField(obj, ['kind', 'type', 'label']),\n obj,\n )\n const text = textFromHitObject(obj, kind)\n if (!text) return null\n const id = stringField(obj, ['id', 'memoryId', 'uuid']) ?? stableId('mem', text)\n return {\n id,\n uri: stringField(obj, ['uri']) ?? `memory://${adapterId}/${encodeURIComponent(id)}`,\n kind,\n text,\n title: stringField(obj, ['title', 'name', 'task', 'subject']),\n score: numberField(obj, ['score']),\n normalizedScore: numberField(obj, ['normalizedScore', 'normalized_score']),\n confidence: numberField(obj, ['confidence']),\n createdAt: stringField(obj, ['createdAt', 'created_at']),\n validUntil: stringField(obj, ['validUntil', 'valid_until']),\n lastVerifiedAt: stringField(obj, ['lastVerifiedAt', 'last_verified_at']),\n metadata: obj,\n }\n}\n\nfunction memoryKind(\n value: string | undefined,\n obj: Record<string, unknown> = {},\n): AgentMemoryHit['kind'] {\n if (\n value === 'message' ||\n value === 'entity' ||\n value === 'fact' ||\n value === 'preference' ||\n value === 'observation' ||\n value === 'reasoning-trace'\n ) {\n return value\n }\n if ('role' in obj && 'content' in obj) return 'message'\n if ('name' in obj && ('type' in obj || 'entityType' in obj)) return 'entity'\n if ('preference' in obj && 'category' in obj) return 'preference'\n if ('task' in obj && 'steps' in obj) return 'reasoning-trace'\n return 'fact'\n}\n\nfunction rawHitsFrom(value: unknown): unknown[] {\n if (Array.isArray(value)) return value\n const obj = record(value)\n if (!obj) return typeof value === 'string' ? [value] : []\n if (Array.isArray(obj.hits)) return obj.hits\n if (Array.isArray(obj.results)) return obj.results\n if (Array.isArray(obj.messages)) return obj.messages\n if (Array.isArray(obj.recentMessages)) return obj.recentMessages\n if (Array.isArray(obj.observations)) return obj.observations\n if (Array.isArray(obj.reflections)) return obj.reflections\n if (typeof obj.content === 'string' || typeof obj.text === 'string') return [obj]\n return []\n}\n\nfunction textFromHitObject(\n obj: Record<string, unknown>,\n kind: AgentMemoryHit['kind'],\n): string | undefined {\n const direct = stringField(obj, [\n 'text',\n 'content',\n 'body',\n 'summary',\n 'preference',\n 'description',\n ])\n if (direct) return direct\n if (kind === 'entity') return stringField(obj, ['name'])\n if (kind === 'fact') {\n const subject = stringField(obj, ['subject'])\n const predicate = stringField(obj, ['predicate'])\n const object = stringField(obj, ['object', 'obj'])\n if (subject && predicate && object) return `${subject} ${predicate} ${object}`\n }\n if (kind === 'reasoning-trace') {\n const task = stringField(obj, ['task'])\n const outcome = stringField(obj, ['outcome'])\n return [task, outcome].filter(Boolean).join('\\n') || undefined\n }\n return undefined\n}\n\nfunction normalizeConversationContextHits(\n value: unknown,\n options: AgentMemorySearchOptions,\n adapterId: string,\n): AgentMemoryHit[] {\n const obj = record(value)\n if (!obj) return normalizeHits(value, options, adapterId)\n const raw = [\n ...rawHitsFrom(obj.reflections).map((hit) => tagContextHit(hit, 'observation', 'Reflection')),\n ...rawHitsFrom(obj.observations).map((hit) => tagContextHit(hit, 'observation', 'Observation')),\n ...rawHitsFrom(obj.recentMessages).map((hit) => tagContextHit(hit, 'message')),\n ]\n return raw.length > 0\n ? normalizeHits(raw, options, adapterId)\n : normalizeHits(value, options, adapterId)\n}\n\nfunction tagContextHit(\n value: unknown,\n kind: AgentMemoryHit['kind'],\n title?: string,\n): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? { kind, title, ...(value as Record<string, unknown>) }\n : { kind, title, content: value }\n}\n\nfunction renderHits(hits: AgentMemoryHit[]): string {\n return hits.map((hit) => hit.text).join('\\n\\n')\n}\n\nfunction idFromResult(value: unknown): string | undefined {\n const obj = record(value)\n return obj ? stringField(obj, ['id', 'memoryId', 'uuid']) : undefined\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction stringField(obj: Record<string, unknown>, names: string[]): string | undefined {\n for (const name of names) {\n const value = obj[name]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\nfunction numberField(obj: Record<string, unknown>, names: string[]): number | undefined {\n for (const name of names) {\n const value = obj[name]\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\nfunction neo4jMessageRole(role: AgentMemoryWriteInput['role']): 'system' | 'user' | 'assistant' {\n return role === 'tool' ? 'assistant' : (role ?? 'user')\n}\n\nfunction stringMetadata(\n metadata: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const value = metadata?.[key]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n","import type { ToolDefinition } from '@tangle-network/agent-interface'\nimport { z } from 'zod'\nimport { sha256 } from '../ids'\nimport type { AgentMemoryBranch, AgentMemoryBranchSnapshot } from './branch'\nimport { canonicalMemoryJson } from './json'\nimport { AgentMemoryKindSchema } from './schemas'\nimport type { AgentMemoryContext, AgentMemoryWriteInput, AgentMemoryWriteResult } from './types'\n\nexport interface PlayMemoryRetrievalReceipt {\n branchId: string\n adapterId: string\n actorId: string\n query: string\n context: AgentMemoryContext\n receiptDigest: `sha256:${string}`\n}\n\nexport interface CreatePlayMemoryToolsOptions {\n branch: AgentMemoryBranch\n actorId: string\n /** Persist through the host's existing record owner before acknowledging a write. */\n onCheckpoint(snapshot: AgentMemoryBranchSnapshot): Promise<void> | void\n recordRetrieval?(receipt: PlayMemoryRetrievalReceipt): Promise<void> | void\n /** Optional transport prefix; tool suffixes remain memory_recall and memory_record. */\n namePrefix?: string\n maxTextChars?: number\n maxResults?: number\n}\n\n// Every resolver for a play shares one branch owner, including its checkpoint publication order.\nconst publications = new WeakMap<\n AgentMemoryBranch,\n {\n tail: Promise<unknown>\n pending?: { input: AgentMemoryWriteInput; result?: AgentMemoryWriteResult }\n }\n>()\n\nexport function createPlayMemoryTools(options: CreatePlayMemoryToolsOptions): ToolDefinition[] {\n if (!options.actorId?.trim()) throw new Error('play memory tools require a trusted actorId')\n if (typeof options.onCheckpoint !== 'function')\n throw new Error('play memory tools require durable checkpoint publication')\n const maxTextChars = options.maxTextChars ?? 8_000\n const maxResults = options.maxResults ?? 20\n if (\n !Number.isSafeInteger(maxTextChars) ||\n maxTextChars < 1 ||\n maxTextChars > 100_000 ||\n !Number.isSafeInteger(maxResults) ||\n maxResults < 1 ||\n maxResults > 100\n )\n throw new Error('invalid play memory tool bounds')\n const prefix = options.namePrefix ?? ''\n if (!/^[a-zA-Z0-9_-]*$/.test(prefix)) throw new Error('invalid memory tool namePrefix')\n const recall = z.strictObject({\n question: z.string().trim().min(1).max(8_000),\n limit: z.int().min(1).max(maxResults).optional(),\n })\n const record = z.strictObject({\n id: z.string().trim().min(1).max(256),\n kind: AgentMemoryKindSchema,\n text: z.string().min(1).max(maxTextChars),\n title: z.string().max(512).optional(),\n sourceRefs: z.array(z.string().min(1).max(2_048)).max(50).optional(),\n })\n return [\n tool(\n `${prefix}memory_recall`,\n 'Recall memory visible to this play. Returned memories are attributed provider evidence, not independently verified findings.',\n recall,\n async (input) => {\n const context = await options.branch.getContext(input.question, {\n limit: input.limit ?? maxResults,\n })\n const content = {\n branchId: options.branch.branchId,\n adapterId: options.branch.id,\n actorId: options.actorId,\n query: input.question,\n context,\n }\n const receipt: PlayMemoryRetrievalReceipt = {\n ...content,\n receiptDigest: `sha256:${sha256(canonicalMemoryJson(content))}`,\n }\n await options.recordRetrieval?.(receipt)\n return { ...context, receipt }\n },\n ),\n tool(\n `${prefix}memory_record`,\n 'Retain a sourced observation in this play and checkpoint its accepted input. Reuse the same id and bytes after an ambiguous response.',\n record,\n async (input) => {\n const write: AgentMemoryWriteInput = {\n id: input.id,\n kind: input.kind,\n text: input.text,\n ...(input.title === undefined ? {} : { title: input.title }),\n metadata: { actorId: options.actorId, sourceRefs: input.sourceRefs ?? [] },\n }\n let state = publications.get(options.branch)\n if (!state) {\n state = { tail: Promise.resolve() }\n publications.set(options.branch, state)\n }\n const shared = state\n const publication = shared.tail\n .catch(() => undefined)\n .then(async () => {\n if (\n shared.pending &&\n canonicalMemoryJson(shared.pending.input) !== canonicalMemoryJson(write)\n ) {\n throw new Error(\n 'reconcile the prior memory write with its same id, bytes, and actor before another write',\n )\n }\n // An unresolved provider operation blocks snapshot flush. Reconcile it before that barrier.\n if (!shared.pending) {\n const before = await options.branch.snapshot()\n const existing = before.journal.find((entry) => entry.input.id === input.id)\n if (existing && canonicalMemoryJson(existing.input) !== canonicalMemoryJson(write))\n throw new Error('memory write id already names different content or attribution')\n shared.pending = { input: write, ...(existing ? { result: existing.result } : {}) }\n }\n const result = shared.pending.result ?? (await options.branch.write(write))\n shared.pending.result = result\n if (!result.accepted) {\n shared.pending = undefined\n return { ...result, checkpointDigest: null }\n }\n const snapshot = await options.branch.snapshot()\n await options.onCheckpoint(snapshot)\n shared.pending = undefined\n return { ...result, checkpointDigest: snapshot.digest }\n })\n shared.tail = publication\n return publication\n },\n ),\n ]\n}\n\nfunction tool<T>(\n name: string,\n description: string,\n inputSchema: z.ZodType<T>,\n handler: (input: T) => Promise<unknown>,\n): ToolDefinition {\n return {\n name,\n description,\n inputSchema,\n inputSchemaJson: z.toJSONSchema(inputSchema) as Record<string, unknown>,\n handler: async (input: unknown) => handler(inputSchema.parse(input)),\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,SAAgB,iBAAiB,KAAqB;CACpD,OAAO,WAAW,OAAO,SAAS,OAAO,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AAClE;AAMA,SAASA,gBAAc,OAAwB;CAC7C,IAAI,OAAO,UAAU,UACnB,MAAM,IAAI,UAAU,mEAAmE;CAEzF,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAIA,eAAa,CAAC,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