cogmemory 0.0.1-beta.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cognitive-memory.cjs","sources":["../src/errors.ts","../src/client.ts","../src/resources/context.ts","../src/resources/memories.ts","../src/resources/recall.ts","../src/resources/self-model.ts","../src/resources/stats.ts","../src/resources/tensions.ts","../src/resources/turns.ts","../src/cogmem.ts","../src/helpers/turn.ts","../src/cognitive/fast-gate.ts","../src/cognitive/relevance.ts","../src/cognitive/memory.ts","../src/cognitive/rules.ts"],"sourcesContent":["import type { CognitiveMemoryErrorBody } from \"./types\"\n\n/**\n * One error class for every failure the service can produce.\n *\n * The service already returns a structured envelope — a tag, a message, the\n * scope that was missing, the fields that failed validation — so the SDK's job is\n * to hand that over as a typed object instead of making callers dig through\n * `error.response.data`.\n *\n * The predicate methods exist so callers ask semantic questions. `status === 403`\n * scatters a magic number through every integration and means something slightly\n * different at each one; `isScopeError()` means the same thing everywhere.\n */\nexport class CognitiveMemoryError extends Error {\n /**\n * Set as a real value, because a minifier renames the class and that silently\n * changes what monitoring groups on. `error.name` is correct either way — the\n * constructor assigns it — but `SomeError.name` and `error.constructor.name`\n * are how a reporter identifies a class, and a minified `\"h\"` breaks that.\n */\n static override readonly name = \"CognitiveMemoryError\"\n\n /** The service's own tag: `Unauthorized`, `Forbidden`, `InvalidRequest`, … */\n readonly code: string\n readonly status: number\n /** Present on a 403: the scope the key would have needed. */\n readonly requiredScope?: string\n /** Present on a 400: which field, and why. */\n readonly issues?: string[]\n readonly body?: CognitiveMemoryErrorBody\n\n constructor(\n message: string,\n init: {\n status: number\n code: string\n body?: CognitiveMemoryErrorBody\n requiredScope?: string\n issues?: string[]\n }\n ) {\n super(message)\n this.name = \"CognitiveMemoryError\"\n this.status = init.status\n this.code = init.code\n this.body = init.body\n this.requiredScope = init.requiredScope\n this.issues = init.issues\n\n // Keeps the constructor out of the stack, so the first frame is the caller.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CognitiveMemoryError)\n }\n }\n\n /** The key is missing, malformed, expired or revoked. */\n isAuthError(): boolean {\n return this.status === 401\n }\n\n /** The key is valid but lacks a scope. `requiredScope` says which. */\n isScopeError(): boolean {\n return this.status === 403\n }\n\n /** The request body did not match the schema. `issues` says where. */\n isValidationError(): boolean {\n return this.status === 400\n }\n\n /** Nothing exists at that id — or it belongs to another organisation. */\n isNotFoundError(): boolean {\n return this.status === 404\n }\n\n isRateLimitError(): boolean {\n return this.status === 429\n }\n\n /** A dependency of ours failed, not the request. Safe to retry. */\n isServerError(): boolean {\n return this.status >= 500\n }\n}\n","import { FetchError, ofetch, type $Fetch } from \"ofetch\"\n\nimport { CognitiveMemoryError } from \"./errors\"\nimport type { CognitiveMemoryConfig, CognitiveMemoryErrorBody } from \"./types\"\n\n/**\n * Configuration, as a factory rather than a constructor.\n *\n * A constructor with fifteen options is a dumping ground: configuration and\n * instantiation get tangled, tests have to construct a whole class to check one\n * header, and \"the client with a different timeout\" becomes a subclass. A factory\n * is a plain function — no `new`, no `this`, composable, trivially mockable.\n *\n * The real work happens in the interceptors. Authentication, error translation\n * and debug logging are configured once here instead of being repeated in each\n * of the twenty-odd methods below, which is the difference between changing how\n * auth works in one place and in twenty.\n */\nexport function createHttpClient(config: CognitiveMemoryConfig): $Fetch {\n const {\n apiKey,\n baseUrl = defaultBaseUrl(),\n timeout = 30_000,\n retry = 2,\n debug = false,\n headers: extraHeaders = {}\n } = config\n\n if (typeof apiKey !== \"string\" || apiKey.trim() === \"\") {\n throw new Error(\n \"cognitive-memory: apiKey is required. Issue one in the dashboard — the secret is shown only once.\"\n )\n }\n\n const inner = ofetch.create({\n baseURL: `${baseUrl.replace(/\\/$/, \"\")}/api/v1`,\n timeout,\n // Retries are for transport hiccups, not for a 400. ofetch already limits\n // this to idempotent-looking methods, and the service is idempotent for the\n // reads that matter.\n retry,\n headers: {\n accept: \"application/json\",\n ...extraHeaders\n },\n\n onRequest({ options, request }) {\n // `options.headers` is a Headers instance by this point, not a plain\n // object — assigning to it silently drops every header.\n options.headers.set(\"authorization\", `Bearer ${apiKey}`)\n options.headers.set(\"content-type\", \"application/json\")\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\"[cognitive-memory]\", options.method ?? \"GET\", `${options.baseURL ?? \"\"}${request ?? \"\"}`)\n }\n },\n\n onResponse({ response, options, request }) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\"[cognitive-memory]\", response.status, options.method ?? \"GET\", request ?? \"\")\n }\n },\n\n })\n\n /**\n * Error translation happens out here rather than in `onResponseError`.\n *\n * ofetch 1.4 replaces anything thrown from that hook with its own `FetchError`\n * before it reaches the caller, so a hook that throws is a hook whose error\n * silently disappears — the caller gets an exception with no status, no scope\n * and no issues. Catching here is the only place the service's envelope can be\n * read, and it leaves genuine transport failures (no response) untouched.\n */\n // The parameter types are taken from `$Fetch` itself rather than restated, so\n // this wrapper cannot drift out of step with the client it wraps.\n const wrap = async (request: unknown, options?: unknown): Promise<unknown> => {\n try {\n return await (inner as (r: unknown, o?: unknown) => Promise<unknown>)(request, options)\n } catch (error) {\n if (!(error instanceof FetchError) || !error.response) throw error\n const response = error.response\n // The service always answers with this envelope; a proxy or a crash in\n // front of it might not, so the body is treated as untrusted.\n const body = (response._data ?? undefined) as CognitiveMemoryErrorBody | undefined\n throw new CognitiveMemoryError(body?.message ?? `cognitive-memory: request failed with ${response.status}`, {\n status: response.status,\n code: body?.error ?? \"UnknownError\",\n ...(body === undefined ? {} : { body }),\n ...(body?.requiredScope === undefined ? {} : { requiredScope: body.requiredScope }),\n ...(body?.issues === undefined ? {} : { issues: body.issues })\n })\n }\n }\n\n return wrap as unknown as $Fetch\n}\n\nfunction defaultBaseUrl(): string {\n if (typeof window !== \"undefined\") return window.location.origin\n return \"http://localhost:3000\"\n}\n\nexport type HttpClient = ReturnType<typeof createHttpClient>\n","import type { HttpClient } from \"../client\"\nimport type { ContextReport, ContextRequest } from \"../types\"\n\n/**\n * The prompt block.\n *\n * One call per turn, and the reason the service exists: a one-line index of\n * everything remembered, plus full bodies only where a named identifier, an\n * unresolved contradiction, or a weak domain earned them.\n */\nexport class ContextResource {\n constructor(private readonly client: HttpClient) {}\n\n build(request: ContextRequest = {}): Promise<ContextReport> {\n return this.client<ContextReport>(\"/context\", { method: \"POST\", body: request })\n }\n}\n","import type { HttpClient } from \"../client\"\nimport type { LearnResult, ListMemoriesParams, Memory, MemoryTier, RememberRequest } from \"../types\"\n\n/**\n * Reading and writing what is stored.\n *\n * Deliberately thin: one method, one endpoint, no cleverness. The class is a\n * namespace, so `memory.memories.` offers the whole surface in an editor, but it\n * is not a place for business logic. The workflow that composes these calls lives\n * in `../helpers`.\n */\nexport class MemoriesResource {\n constructor(private readonly client: HttpClient) {}\n\n /**\n * The envelope is unwrapped here rather than passed on.\n *\n * The service replies with `{ memories, stats }` so a dashboard can get both in\n * one call, but an SDK caller who asked for a list wants a list. Deciding that\n * in one place here is better than making every integration know the shape.\n */\n async list(params: ListMemoriesParams = {}): Promise<Memory[]> {\n const response = await this.client<{ memories: Memory[] }>(\"/memories\", {\n method: \"GET\",\n query: params\n })\n return response.memories\n }\n\n async get(id: string): Promise<Memory> {\n const response = await this.client<{ memory: Memory }>(`/memories/${encodeURIComponent(id)}`, {\n method: \"GET\"\n })\n return response.memory\n }\n\n /**\n * State facts outright.\n *\n * Restatements of something already held are folded in rather than stored\n * twice, and the result says which ones were folded and into what — a write\n * that silently did nothing is indistinguishable from a bug.\n */\n create(request: RememberRequest): Promise<LearnResult> {\n return this.client<LearnResult>(\"/memories\", { method: \"POST\", body: request })\n }\n\n /** Move a memory between tiers. L1 is pre-staged into every context build. */\n async promote(id: string, tier: MemoryTier): Promise<Memory> {\n const response = await this.client<{ memory: Memory }>(`/memories/${encodeURIComponent(id)}`, {\n method: \"PATCH\",\n body: { tier }\n })\n return response.memory\n }\n\n remove(id: string): Promise<{ deleted: boolean; id: string }> {\n return this.client(`/memories/${encodeURIComponent(id)}`, { method: \"DELETE\" })\n }\n}\n","import type { HttpClient } from \"../client\"\nimport type { RecallRequest, RecallResponse } from \"../types\"\n\n/**\n * Deterministic ranked lookup.\n *\n * No model is involved, so recall quality does not change when a provider is\n * down or a different model is configured. `empty: true` is the signal to admit\n * ignorance rather than guess.\n */\nexport class RecallResource {\n constructor(private readonly client: HttpClient) {}\n\n search(request: RecallRequest): Promise<RecallResponse> {\n return this.client<RecallResponse>(\"/recall\", { method: \"POST\", body: request })\n }\n}\n","import type { HttpClient } from \"../client\"\nimport type { DomainOutcomeRequest, SelfModel } from \"../types\"\n\n/**\n * The proprioceptive self-model: how reliably this agent has done in each domain.\n *\n * Nothing here is inferred. Without outcomes recorded through `record`, the\n * model stays at its priors and no guardrail ever fires — which is the most\n * common reason a self-model looks like it is not working.\n */\nexport class SelfModelResource {\n constructor(private readonly client: HttpClient) {}\n\n get(): Promise<SelfModel> {\n return this.client<SelfModel>(\"/self-model\", { method: \"GET\" })\n }\n\n record(request: DomainOutcomeRequest): Promise<SelfModel> {\n return this.client<SelfModel>(\"/self-model/outcome\", { method: \"POST\", body: request })\n }\n}\n","import type { HttpClient } from \"../client\"\nimport type { Health, Stats } from \"../types\"\n\n/** What the memory currently holds, and what the service can do. */\nexport class StatsResource {\n constructor(private readonly client: HttpClient) {}\n\n /** Needs only `stats:read`, so monitoring can watch without reading memories. */\n get(): Promise<Stats> {\n return this.client<Stats>(\"/stats\", { method: \"GET\" })\n }\n}\n\n/**\n * Liveness, and this deployment's limits and extractor mode.\n *\n * Takes an explicit base URL because it is the one call that must work with no\n * key at all — including from a health check that has no credentials.\n */\nexport const fetchHealth = async (baseUrl: string): Promise<Health> => {\n const origin = baseUrl.replace(/\\/$/, \"\")\n const response = await fetch(`${origin}/api/v1/health`, { headers: { accept: \"application/json\" } })\n if (!response.ok) {\n throw new Error(`cognitive-memory: health check failed with ${response.status}`)\n }\n return (await response.json()) as Health\n}\n","import type { HttpClient } from \"../client\"\nimport type { AddTensionRequest, ResolveTensionRequest, Tension, TensionStatus } from \"../types\"\n\n/**\n * Knowledge tensions: two claims that cannot both be true.\n *\n * A tension is worth more than either claim alone, so it is pinned into every\n * context build with an actionable question until it is resolved.\n */\nexport class TensionsResource {\n constructor(private readonly client: HttpClient) {}\n\n async list(status?: TensionStatus): Promise<Tension[]> {\n const response = await this.client<{ tensions: Tension[] }>(\"/tensions\", {\n method: \"GET\",\n query: status === undefined ? {} : { status }\n })\n return response.tensions\n }\n\n async create(request: AddTensionRequest): Promise<Tension> {\n const response = await this.client<{ tension: Tension }>(\"/tensions\", {\n method: \"POST\",\n body: request\n })\n return response.tension\n }\n\n async resolve(id: string, request: ResolveTensionRequest): Promise<Tension> {\n const response = await this.client<{ tension: Tension }>(`/tensions/${encodeURIComponent(id)}`, {\n method: \"POST\",\n body: request\n })\n return response.tension\n }\n}\n","import type { HttpClient } from \"../client\"\nimport type { LearnResult, TurnRequest } from \"../types\"\n\n/**\n * Learning from a completed turn.\n *\n * A turn whose user message contains a question is treated as a lookup rather\n * than a lesson, so this is called after work is done, not before.\n */\nexport class TurnsResource {\n constructor(private readonly client: HttpClient) {}\n\n learn(request: TurnRequest): Promise<LearnResult> {\n return this.client<LearnResult>(\"/turns\", { method: \"POST\", body: request })\n }\n}\n","import { createHttpClient, type HttpClient } from \"./client\"\nimport { ContextResource } from \"./resources/context\"\nimport { MemoriesResource } from \"./resources/memories\"\nimport { RecallResource } from \"./resources/recall\"\nimport { SelfModelResource } from \"./resources/self-model\"\nimport { StatsResource } from \"./resources/stats\"\nimport { TensionsResource } from \"./resources/tensions\"\nimport { TurnsResource } from \"./resources/turns\"\nimport type { Health, CognitiveMemoryConfig } from \"./types\"\nimport { fetchHealth } from \"./resources/stats\"\n\n/**\n * The client.\n *\n * Named `Cogmem` rather than `CognitiveMemory` because that name belongs to the\n * in-process engine, and has for as long as this layer existed. Two exports\n * cannot share a name, and the engine's is the older public API: quietly\n * redefining it to mean an HTTP client would break every consumer of it.\n *\n * Resource classes rather than a flat list of functions, because\n * `memory.memories.` in an editor shows every operation on memories and nothing\n * else. The methods stay one-to-one with endpoints, so the class never becomes a\n * second, divergent copy of the service.\n *\n * `readonly` on the resources is not decoration: it stops a caller reassigning\n * `memory.memories` and wondering why the other half of the client stopped\n * seeing the change.\n */\nexport class Cogmem {\n private readonly client: HttpClient\n readonly baseUrl: string\n\n readonly memories: MemoriesResource\n readonly context: ContextResource\n readonly recall: RecallResource\n readonly turns: TurnsResource\n readonly tensions: TensionsResource\n readonly selfModel: SelfModelResource\n readonly stats: StatsResource\n\n constructor(config: CognitiveMemoryConfig) {\n this.baseUrl = (config.baseUrl ?? \"http://localhost:3000\").replace(/\\/$/, \"\")\n this.client = createHttpClient(config)\n this.memories = new MemoriesResource(this.client)\n this.context = new ContextResource(this.client)\n this.recall = new RecallResource(this.client)\n this.turns = new TurnsResource(this.client)\n this.tensions = new TensionsResource(this.client)\n this.selfModel = new SelfModelResource(this.client)\n this.stats = new StatsResource(this.client)\n }\n\n /**\n * Liveness and limits, without spending a request on the configured key.\n *\n * Useful in a readiness probe: if `extractor` is `rules-only` the service is up\n * but is not doing model-backed extraction, and `problems` is non-empty when a\n * setting is present but unusable.\n */\n health(): Promise<Health> {\n return fetchHealth(this.baseUrl)\n }\n}\n\n/**\n * Both construction styles, deliberately.\n *\n * Some people prefer `new Cogmem(...)` and some prefer `createClient(...)`; there\n * is no reason to make anyone rename. The factory is also the easier one to mock\n * in tests, which is the whole reason `createHttpClient` is a function.\n */\nexport function createClient(config: CognitiveMemoryConfig): Cogmem {\n return new Cogmem(config)\n}\n","import type { Cogmem } from \"../cogmem\"\nimport type { ContextReport, LearnResult, Memory } from \"../types\"\n\n/**\n * Workflows.\n *\n * Resource methods are one call each. These compose them into the sequences\n * people actually get wrong when they write the loop themselves — and the\n * mistakes are mundane: forgetting to learn from a turn, learning from a question,\n * letting a memory failure take down the turn it was meant to help, or never\n * telling the service how a task went so the guardrails never fire.\n *\n * Each helper takes the client explicitly rather than closing over one, so it\n * works with a second client without a module-level singleton.\n */\n\nexport interface TurnOptions {\n /** Groups everything learned in one conversation. */\n sessionId?: string\n /**\n * What the turn turned out to be about, e.g. `\"database\"`.\n *\n * Recorded against the self-model, which is what eventually produces a\n * guardrail for a domain the agent keeps failing in. Cheap to send and the\n * difference between a self-model that learns and one that sits at its priors.\n */\n domain?: string\n /** What went wrong, when the turn was a failure. */\n failurePattern?: string\n /** What worked, when the turn was a success. */\n strategy?: string\n /** Set false to skip learning — a retrieval-only turn, say. */\n learn?: boolean\n onLearn?: (result: LearnResult) => void\n}\n\nexport interface RunTurnResult {\n context: ContextReport\n learning: LearnResult | null\n /**\n * Why learning did not happen, if it did not.\n *\n * Present because a silent skip looks identical to a working one until the\n * thing you taught it never comes back.\n */\n learningSkipped?: string\n}\n\n/**\n * One turn of an agent loop, with memory handled correctly.\n *\n * The order is the point:\n *\n * 1. build context *before* the model runs, keyed on the message being answered;\n * 2. run the model;\n * 3. learn from the finished exchange;\n * 4. record how the domain went, so the self-model moves.\n *\n * Steps 3 and 4 never fail the turn. Memory is an enhancement; an outage in it\n * must not take down the agent that was working fine without it, and the errors\n * are surfaced through `onLearn` and the returned skip reason rather than\n * swallowed.\n */\nexport async function runTurn(\n memory: Cogmem,\n input: {\n userMessage: string\n run: (context: string) => Promise<string>\n },\n options: TurnOptions = {}\n): Promise<RunTurnResult> {\n const context = await memory.context.build({\n userMessage: input.userMessage,\n ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId })\n })\n\n const assistantResponse = await input.run(context.text)\n\n if (options.learn === false) {\n return { context, learning: null, learningSkipped: \"learning disabled for this turn\" }\n }\n\n let learning: LearnResult | null = null\n try {\n learning = await memory.turns.learn({\n userMessage: input.userMessage,\n assistantResponse,\n ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId })\n })\n options.onLearn?.(learning)\n } catch (error) {\n // Deliberately not rethrown: the turn already succeeded, and the assistant's\n // answer does not become wrong because memory could not be written.\n console.warn(\"[cognitive-memory] could not learn from this turn\", error)\n return { context, learning: null, learningSkipped: String(error) }\n }\n\n if (options.domain !== undefined) {\n try {\n await memory.selfModel.record({\n domain: options.domain,\n success: options.failurePattern === undefined,\n ...(options.failurePattern === undefined ? {} : { failurePattern: options.failurePattern }),\n ...(options.strategy === undefined ? {} : { strategy: options.strategy })\n })\n } catch (error) {\n console.warn(\"[cognitive-memory] could not record the domain outcome\", error)\n }\n }\n\n return { context, learning }\n}\n\nexport interface RecallOrExplainOptions {\n limit?: number\n /** Overrides the default \"you were not told this\" wording. */\n emptyMessage?: string\n}\n\n/**\n * Recall, phrased for injection into a prompt.\n *\n * Returns text rather than results because the caller's next step is almost\n * always \"put this in the prompt\", and doing the formatting here means every\n * integration handles the empty case the same way: by saying so, rather than\n * letting a model fill the gap with a guess.\n */\nexport async function recallOrExplain(\n memory: Cogmem,\n query: string,\n options: RecallOrExplainOptions = {}\n): Promise<string> {\n const response = await memory.recall.search({\n query,\n ...(options.limit === undefined ? {} : { limit: options.limit })\n })\n\n if (response.empty) {\n return options.emptyMessage ?? `Nothing in memory matches \"${query}\". If you were not told, say so rather than guessing.`\n }\n\n const lines = response.results.map((hit) => {\n const domains = hit.memory.domains.length > 0 ? ` (${hit.memory.domains.join(\", \")})` : \"\"\n return `- ${hit.memory.content}${domains} [${hit.memory.tier}, relevance ${hit.score.toFixed(2)}]`\n })\n return `Remembered (${response.results.length} match${response.results.length === 1 ? \"\" : \"es\"}):\\n${lines.join(\"\\n\")}`\n}\n\nexport interface SeedOptions {\n /** Statements worth keeping regardless of how they are phrased. */\n facts: string[]\n sessionId?: string\n}\n\n/**\n * Store a set of statements once, tolerating the ones already held.\n *\n * For a migration or a first run, where you have a list of facts and no way to\n * know which the service already knows. Restatements come back under\n * `mergedInto` rather than as errors, so re-running it is safe.\n */\nexport async function seedMemories(memory: Cogmem, options: SeedOptions): Promise<{\n stored: Memory[]\n merged: Memory[]\n rejected: LearnResult[\"rejected\"]\n}> {\n const result = await memory.memories.create({\n items: options.facts.map((content) => ({ content })),\n ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId })\n })\n return { stored: result.stored, merged: result.mergedInto, rejected: result.rejected }\n}\n","/**\n * Fast Heuristic Gate\n * \n * Synchronous, sub-5ms gate running on the critical path before model invocation.\n * Detects explicit user corrections/contradictions and significant domain pivots\n * without triggering an LLM call.\n */\n\nexport interface FastGateResult {\n action: \"proceed\" | \"inject_caution\";\n cautionNote?: string;\n detectedDomains?: string[];\n}\n\nconst CONTRADICTION_PATTERNS = [\n /actually,?\\s+(?:we|i)\\s+(?:switched|changed|moved|migrated|replaced|use|want|have)/i,\n /that(?:'s|\\s+is)\\s+(?:wrong|incorrect|outdated|false|not\\s+right|no\\s+longer)/i,\n /no,?\\s+(?:it(?:'s|\\s+is)|we\\s+use|we\\s+switched|it\\s+should\\s+be|don(?:'t|\\s+not)\\s+use)/i,\n /stop\\s+using\\s+/i,\n /instead\\s+of\\s+/i,\n /disregard\\s+(?:prior|previous|what\\s+i\\s+said)/i,\n];\n\nconst DOMAIN_KEYWORDS: Record<string, RegExp[]> = {\n auth: [/auth/i, /login/i, /session/i, /jwt/i, /oauth/i, /token/i, /password/i, /permission/i],\n database: [/postgres/i, /sqlite/i, /sql/i, /schema/i, /migration/i, /prisma/i, /drizzle/i, /mongo/i, /redis/i],\n frontend: [/css/i, /tailwind/i, /component/i, /jsx/i, /tsx/i, /layout/i, /ui/i, /render/i, /html/i],\n build: [/vite/i, /webpack/i, /turbo/i, /tsconfig/i, /pnpm/i, /package\\.json/i, /bundle/i],\n api: [/rest/i, /graphql/i, /endpoint/i, /route/i, /fetch/i, /request/i, /response/i],\n git: [/branch/i, /commit/i, /merge/i, /rebase/i, /worktree/i, /conflict/i],\n};\n\nexport const runFastGate = (userMessage: string): FastGateResult => {\n if (!userMessage || userMessage.trim().length === 0) {\n return { action: \"proceed\" };\n }\n\n // 1. Check for explicit contradiction signals\n for (const pattern of CONTRADICTION_PATTERNS) {\n if (pattern.test(userMessage)) {\n return {\n action: \"inject_caution\",\n cautionNote: \"User appears to be explicitly correcting a prior premise or configuration. Verify current facts before proceeding with assumptions.\",\n detectedDomains: extractDomains(userMessage),\n };\n }\n }\n\n return {\n action: \"proceed\",\n detectedDomains: extractDomains(userMessage),\n };\n};\n\nexport const extractDomains = (text: string): string[] => {\n const matched: string[] = [];\n for (const [domain, patterns] of Object.entries(DOMAIN_KEYWORDS)) {\n if (patterns.some((p) => p.test(text))) {\n matched.push(domain);\n }\n }\n return matched;\n};\n","/**\n * Deterministic text, relevance and reconciliation primitives.\n *\n * The whole decision layer of a memory system, with no model, no database and\n * no dependencies — so the service, an in-process runtime, and a test all make\n * the same calls. The reasoning behind each threshold is written down because\n * the numbers are only defensible with it:\n *\n * - A memory cannot be found by a model being smart, only by words overlapping.\n * - Lexical overlap peaks on identical strings and bottoms out on the\n * paraphrases that actually add information, so the *recall* floor is low and\n * a separate step decides what to do with what came back.\n * - Losing a fact is permanent; an extra duplicate costs one row. Every\n * threshold below leans that way.\n */\n\nconst STOP_WORDS = new Set([\n \"the\", \"and\", \"for\", \"this\", \"that\", \"with\", \"from\", \"you\", \"are\", \"was\", \"has\", \"have\",\n \"what\", \"which\", \"when\", \"were\", \"will\", \"your\", \"our\", \"its\", \"not\", \"but\", \"all\", \"any\",\n \"can\", \"did\", \"does\", \"how\", \"into\", \"out\", \"use\", \"used\", \"using\", \"one\", \"two\", \"get\",\n \"new\", \"now\", \"then\", \"than\", \"them\", \"they\", \"his\", \"her\", \"she\", \"him\", \"been\", \"being\",\n \"there\", \"here\", \"also\", \"just\", \"like\", \"make\", \"made\", \"need\", \"want\", \"about\", \"after\",\n \"tell\", \"know\", \"give\", \"show\", \"please\", \"would\", \"could\", \"should\", \"shall\"\n])\n\n/** Words that appear in every restatement of a fact and so carry no identity. */\nconst FILLER_TOKENS = new Set([\n \"this\", \"that\", \"these\", \"those\", \"there\", \"here\", \"with\", \"from\", \"into\", \"must\",\n \"should\", \"always\", \"never\", \"under\", \"over\", \"about\", \"after\", \"before\", \"when\",\n \"where\", \"which\", \"what\", \"your\", \"their\", \"them\", \"they\", \"then\", \"than\", \"also\",\n \"just\", \"only\", \"each\", \"every\", \"some\", \"such\", \"very\", \"more\", \"most\", \"same\",\n \"file\", \"files\", \"name\", \"names\", \"project\", \"repository\", \"repo\", \"note\"\n])\n\n/** Content words worth matching a memory against. */\nexport const relevanceTokens = (value: string): Set<string> =>\n new Set(\n value\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((word) => word.length >= 3 && !STOP_WORDS.has(word))\n )\n\n/** Overlap of two token sets, normalised by the smaller side. */\nexport const overlapScore = (query: Set<string>, candidate: Set<string>): number => {\n if (query.size === 0 || candidate.size === 0) return 0\n let shared = 0\n for (const word of query) if (candidate.has(word)) shared += 1\n return shared / Math.min(query.size, candidate.size)\n}\n\n/**\n * Floor for *candidate* recall, not a similarity decision.\n *\n * Deliberately low. This only decides who gets adjudicated; a tight gate misses\n * exactly the paraphrases worth merging.\n */\nexport const CANDIDATE_FLOOR = 0.3\n\n/** Above this, a memory is worth promoting into the pre-staged index. */\nexport const PROMOTE_THRESHOLD = 0.12\n\n/** How many existing memories to put in front of an adjudicator. */\nexport const MAX_CANDIDATES = 8\n\n/** Two results this similar are the same memory, restated. */\nexport const COLLAPSE_THRESHOLD = 0.8\n\n/**\n * Tokens that carry a fact's identity: identifiers, numbers, codes.\n *\n * Function words and generic nouns are dropped because they recur in every\n * restatement and hide real differences.\n */\nexport const distinctiveTokens = (value: string): Set<string> =>\n new Set(\n value\n .toLowerCase()\n .replace(/['']/g, \"\")\n .split(/[^a-z0-9]+/)\n .filter(Boolean)\n .filter((w) => /\\d/.test(w) || w.length >= 4)\n .filter((w) => !FILLER_TOKENS.has(w))\n )\n\n/**\n * Whether rewriting `original` as `replacement` would drop information.\n *\n * Distinctive tokens carry a fact's identity, so a replacement missing one has\n * deleted something — usually the qualifier that made the two statements differ\n * at all (\"never production\", a build id, a port). Trailing plurals are folded\n * so \"deploys\" merging into \"deploy\" is not read as a deletion.\n *\n * Biased towards reporting a loss: a false positive costs a duplicate entry,\n * which is recoverable, while a false negative deletes a fact for good.\n */\nexport const isLossyRewrite = (original: string, replacement: string): boolean => {\n const fold = (tokens: Set<string>): Set<string> =>\n new Set([...tokens].map((t) => (t.length >= 4 && t.endsWith(\"s\") ? t.slice(0, -1) : t)))\n const after = fold(distinctiveTokens(replacement))\n for (const token of fold(distinctiveTokens(original))) {\n if (!after.has(token)) return true\n }\n return false\n}\n\n/**\n * Dotted names that are not prose: hostnames, package names, file names.\n *\n * `internal-hbr-2291.pineapple.example` is precisely the kind of value a user\n * names and a memory holds, and without this the identifier patterns below missed\n * it — the trigger silently never fired for a host, which is one of the cases it\n * exists for. The last label must be alphabetic, which is what keeps version\n * strings and abbreviations out; a short stoplist covers the rest.\n */\nconst HOSTNAME = /\\b[a-z0-9][a-z0-9-]{1,}(?:\\.[a-z0-9-]+)*\\.[a-z]{2,}\\b/gi\n\n/** Dotted tokens that are ordinary writing, not names. */\nconst NOT_A_HOSTNAME = new Set([\n \"eg\", \"ie\", \"etc\", \"vs\", \"approx\", \"inc\", \"ltd\", \"corp\", \"dept\", \"est\", \"fig\", \"no\", \"al\"\n])\n\n/**\n * Identifiers worth matching a memory against: URLs, paths, hostnames,\n * SCREAMING_SNAKE, camelCase, long kebab-case and hex-ish codes.\n *\n * The same idea as Aider's `mentioned_idents`: a user naming a concrete thing\n * is a much stronger signal than the words around it. This is what turns a\n * recall into a full-body injection without asking a model.\n */\nexport const extractIdentifiers = (text: string): string[] => {\n const found = new Set<string>()\n for (const match of text.match(/\\bhttps?:\\/\\/[^\\s<>()[\\]\"'`]+/g) ?? []) found.add(match)\n for (const match of text.match(HOSTNAME) ?? []) {\n if (NOT_A_HOSTNAME.has(match.toLowerCase())) continue\n found.add(match)\n }\n for (const match of text.match(/\\b(?:\\.{0,2}\\/)?[\\w-]+(?:\\/[\\w.-]+)+\\/?/g) ?? []) {\n if (match.length > 3) found.add(match)\n }\n for (const match of text.match(/\\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\\b/g) ?? []) found.add(match)\n for (const match of text.match(/\\b[A-Z]{2,}[0-9][A-Z0-9-]*\\b/g) ?? []) found.add(match)\n for (const match of text.match(/\\b[a-z]+(?:[A-Z][a-z0-9]+){1,}\\b/g) ?? []) found.add(match)\n for (const match of text.match(/\\b[a-z]+(?:-[a-z0-9]+){2,}\\b/g) ?? []) found.add(match)\n for (const match of text.match(/\\b[0-9a-f]{6,}\\b/gi) ?? []) found.add(match)\n return [...found]\n}\n\n/**\n * Instructions about *this conversation* rather than durable facts about the\n * project.\n *\n * \"Do not verify the staging build against the repository\" and \"just remember\n * this\" describe how to behave right now, so storing them produces noise that\n * later looks like a project constraint.\n *\n * Explicit patterns rather than a \"is this specific enough?\" heuristic, because\n * over-filtering would silently lose real memories, which is the worse failure.\n */\nconst INTERACTION_SCOPED = [\n /\\b(?:do not|don'?t|never|no need to)\\s+(?:verify|check|confirm|look\\s?up|search|investigate|browse|resolve)\\b/i,\n /\\bjust\\s+(?:remember|note|acknowledge|retain|treat)\\b/i,\n /\\b(?:held|noted|stored|remembered)\\s+(?:in|for)\\s+(?:this|the)\\s+conversation\\b/i,\n /\\bnot\\s+verified\\b/i,\n /\\bwithout\\s+verifying\\b/i,\n /\\bfor\\s+this\\s+(?:conversation|session|turn|reply|response)\\s+only\\b/i,\n /^(?:ok|okay|noted|got it|sure|thanks)\\b[.!]?$/i\n]\n\nexport const isInteractionScoped = (content: string): boolean =>\n INTERACTION_SCOPED.some((pattern) => pattern.test(content))\n\n/** Similarity of two statements by the tokens that carry identity. */\nexport const similarity = (a: string, b: string): number => {\n const left = distinctiveTokens(a)\n const right = distinctiveTokens(b)\n if (left.size === 0 || right.size === 0) return 0\n let shared = 0\n for (const word of left) if (right.has(word)) shared += 1\n return shared / Math.min(left.size, right.size)\n}\n\nexport const normalise = (value: string): string => value.trim().toLowerCase()\n\n/** Approximate token cost of a string. */\nexport const estimateTokens = (value: string): number => Math.ceil(value.length / 4)\n\n/**\n * The index line: short, scannable, no body.\n *\n * Falling back to the first sentence keeps an index line readable when a memory\n * arrives from the API without a gist.\n */\nexport const gistOf = (item: { readonly content: string; readonly gist?: string | undefined }): string => {\n if (item.gist && item.gist.trim().length > 0) return item.gist.trim()\n const first = item.content.split(/(?<=[.!?])\\s/)[0] ?? item.content\n const trimmed = first.trim()\n return trimmed.length > 90 ? `${trimmed.slice(0, 90)}…` : trimmed\n}\n","import type {\n ArbiterEvaluationResult,\n MemoryInclusionReason,\n MemoryInjectionEntry,\n MemoryInjectionReport,\n MemoryReconciliation,\n ArbiterFn,\n CognitiveMemoryOptions,\n CognitiveMemoryStateSnapshot,\n KnowledgeTension,\n MemoryItem,\n MemoryTier,\n ProprioceptiveSelfModel,\n} from \"./types.js\";\nimport { runFastGate } from \"./fast-gate.js\";\nimport {\n CANDIDATE_FLOOR,\n COLLAPSE_THRESHOLD,\n estimateTokens,\n gistOf,\n distinctiveTokens,\n isInteractionScoped,\n isLossyRewrite,\n MAX_CANDIDATES,\n overlapScore,\n PROMOTE_THRESHOLD,\n relevanceTokens,\n similarity\n} from \"./relevance.js\";\n\n/**\n * CognitiveMemory\n *\n * An intelligent 4-tier cache layer (L0-L3) with:\n * - Anticipatory pre-staging (predicts next turn's needs)\n * - Tension tracking (pinned contradictions in L0)\n * - Proprioceptive self-model (guards weak domains)\n * - Zero added TTFT latency (runs asynchronously post-turn)\n */\n/**\n * Relevance scoring, shared by automatic promotion and on-demand `search()`.\n *\n * It used to be a single domain string compared with `turn.includes(domain)`,\n * which almost never matched: a memory tagged \"naming-conventions\" cannot match\n * a question that says \"naming\". Overlap over content words works because the\n * memory text and the question share the words that identify the fact.\n */\n/*\n * Relevance scoring, merge safety and index formatting all live in\n * `./relevance.ts` rather than here.\n *\n * They used to be private copies in this file, and the same logic was separately\n * reimplemented in the service. Three copies of a merge rule is three chances to\n * disagree about whether a fact was lost, so there is now exactly one, and it is\n * the version with the hostname and containment fixes in it.\n */\n\n/** L1 only starts evicting past this size. */\nconst DEMOTE_ABOVE = 5\n\n\nexport class CognitiveMemory {\n // L0: Pinned core state (identity, self-model, active tensions)\n private activeTensions: Map<string, KnowledgeTension> = new Map();\n private selfModel: ProprioceptiveSelfModel;\n private activeTaskTrace = \"\";\n\n // L1: Hot Cache (pre-staged for upcoming turn)\n private l1HotCache: Map<string, MemoryItem> = new Map();\n\n // L2: Warm Storage (indexed candidates ready for promotion)\n private l2WarmStore: Map<string, MemoryItem> = new Map();\n\n // L3: Cold Archive (historical, loaded on demand)\n private l3ColdArchive: Map<string, MemoryItem> = new Map();\n\n private maxL0Tokens: number;\n private maxL1Tokens: number;\n /** Ceiling on everything injected into one prompt, index and bodies together. */\n private maxTotalTokens: number;\n private arbiter: ArbiterFn | null = null;\n private autoExtractMemories: boolean;\n /** Model-backed turn extractor; the regex fallback runs when this is absent. */\n private reconcile?: CognitiveMemoryOptions[\"reconcile\"];\n private extract?: (turn: { userMessage: string; assistantResponse: string }) => Promise<{\n memories: Array<{ content: string; domains?: string[] }>;\n tensions?: Array<{\n claimA: string;\n claimB: string;\n impact: \"low\" | \"medium\" | \"critical\";\n actionableQuestion: string;\n }>;\n }>;\n private onPersist?: (state: CognitiveMemoryStateSnapshot) => Promise<void> | void;\n\n private stats = {\n totalTurnsProcessed: 0,\n predictionsHit: 0,\n predictionsTotal: 0,\n tensionsDetected: 0,\n };\n\n constructor(options: CognitiveMemoryOptions = {}) {\n this.maxL0Tokens = options.maxL0Tokens ?? 2000;\n this.maxL1Tokens = options.maxL1Tokens ?? 8000;\n this.maxTotalTokens = options.maxTotalTokens ?? 2000;\n this.arbiter = options.arbiter ?? null;\n this.autoExtractMemories = options.autoExtractMemories ?? true;\n this.extract = options.extract;\n this.reconcile = options.reconcile;\n this.onPersist = options.onPersist;\n\n this.selfModel = {\n domains: options.initialSelfModel?.domains ?? {},\n calibrationFactor: options.initialSelfModel?.calibrationFactor ?? 1.0,\n activeDomains: options.initialSelfModel?.activeDomains ?? [],\n };\n }\n\n /**\n * Sub-1ms synchronous call to produce the prompt context block.\n * Concatenates L0 (active tensions + self-model) and pre-staged L1.\n * Adds zero latency to TTFT.\n */\n /**\n * Decide what goes into this turn's prompt, and record why.\n *\n * Follows the index/body split that Claude Code's `MEMORY.md` and Letta's\n * progressive disclosure both converged on: a short index of every memory is\n * always present, and a body is only spent where a deterministic signal earned\n * it. Always injecting bodies costs an order of magnitude more tokens and, per\n * Chroma's context-rot work, injects distractors by construction.\n *\n * @param forceFull memory ids whose body should be included regardless of tier.\n */\n planInjection(options: { userMessage?: string; forceFull?: Iterable<string> } = {}): MemoryInjectionReport {\n const force = new Set(options.forceFull ?? []);\n const sections: string[] = [];\n const entries: MemoryInjectionEntry[] = [];\n let used = 0;\n let truncated = false;\n\n const include = (\n item: MemoryItem,\n reason: MemoryInclusionReason,\n withBody: boolean\n ): void => {\n const gist = gistOf(item);\n const body = withBody ? item.content : undefined;\n const tags = item.metadata.domains.slice(0, 3);\n const suffix = tags.length > 0 ? ` (${tags.join(\", \")})` : \"\";\n const tokens = estimateTokens(`${gist}${suffix}${body ?? \"\"}`);\n if (used + tokens > this.maxTotalTokens) {\n truncated = true;\n return;\n }\n used += tokens;\n entries.push({ id: item.id, tier: item.tier, reason, gist, body, tokens });\n };\n\n // Fast gate: catch a contradiction in what the user just said.\n if (options.userMessage) {\n const gate = runFastGate(options.userMessage);\n if (gate.action === \"inject_caution\" && gate.cautionNote) {\n sections.push(`### ⚠️ Correction Detected In This Message\\n${gate.cautionNote}`);\n }\n }\n\n // Weak-domain warnings: domains this agent is unreliable in.\n const weakDomains = this.selfModel.activeDomains\n .map((d) => ({ d, capability: this.selfModel.domains[d] }))\n .filter((x) => x.capability && x.capability.reliabilityScore < 0.75);\n if (weakDomains.length > 0) {\n const lines = weakDomains.map(({ d, capability }) => {\n const cap = capability!;\n include(\n {\n id: `guardrail-${d}`,\n content: `${d}: reliability ${Math.round(cap.reliabilityScore * 100)}% over ${cap.sampleCount} tasks.${\n cap.knownFailurePatterns.length > 0 ? ` Known pitfalls: ${cap.knownFailurePatterns.join(\"; \")}` : \"\"\n }${cap.recommendedStrategies.length > 0 ? ` Approach: ${cap.recommendedStrategies.join(\"; \")}` : \"\"}`,\n bookmark: `${d} weak domain`,\n tier: \"L0\",\n metadata: { domains: [d], createdAt: Date.now(), lastAccessedAt: Date.now(), accessCount: 0 },\n },\n \"guardrail\",\n true,\n );\n return `- ${d} (${Math.round(cap.reliabilityScore * 100)}% reliable): ${\n cap.knownFailurePatterns.join(\"; \") || \"be careful\"\n }`;\n });\n sections.push(`### Weak Domains — Under 75% Reliability\\n${lines.join(\"\\n\")}`);\n }\n\n // Index: one line per memory, bodies withheld unless a trigger earned them.\n const indexLines: string[] = [];\n for (const item of this.l1HotCache.values()) {\n const tags = item.metadata.domains.slice(0, 3);\n const suffix = tags.length > 0 ? ` (${tags.join(\", \")})` : \"\";\n if (force.has(item.id)) {\n include(item, \"trigger\", true);\n indexLines.push(`- ${item.content}${suffix}`);\n } else {\n include(item, \"index\", false);\n indexLines.push(`- ${gistOf(item)}${suffix}`);\n }\n }\n if (indexLines.length > 0) {\n sections.push(\n [\n \"### Memory index — established earlier in this project\",\n \"One line per remembered item. Use `recall` to pull a full item, then treat it as true.\",\n ...indexLines,\n ].join(\"\\n\"),\n );\n }\n\n // Unresolved contradictions earn full bodies: they are prompts to clarify, not trivia.\n const activeTensions = [...this.activeTensions.values()].filter((t) => t.status === \"active\");\n if (activeTensions.length > 0) {\n const lines = activeTensions.map((t) => {\n include(\n {\n id: t.id,\n content: `${t.claimA.statement} vs ${t.claimB.statement} — ${t.actionableQuestion}`,\n bookmark: t.claimA.statement,\n tier: \"L0\",\n metadata: { domains: [], createdAt: t.claimA.timestamp, lastAccessedAt: Date.now(), accessCount: 0 },\n },\n \"tension\",\n true,\n );\n return `- [${t.impact.toUpperCase()}] \"${t.claimA.statement}\" conflicts with \"${t.claimB.statement}\". Ask: ${t.actionableQuestion}`;\n });\n sections.push(`### Unresolved Contradictions\\n${lines.join(\"\\n\")}`);\n }\n\n return {\n text: sections.length > 0 ? `\\n## Cognitive Memory State\\n${sections.join(\"\\n\\n\")}\\n` : \"\",\n entries,\n totalTokens: used,\n truncated,\n };\n }\n\n /** Prompt text only. Prefer `planInjection` when you want to log what went in. */\n getPromptContext(currentUserMessage?: string): string {\n return this.planInjection({ userMessage: currentUserMessage }).text;\n }\n\n /**\n * Search every tier for memories relevant to `query`.\n *\n * This is the on-demand path, exposed to the agent as a tool. Pre-staging into\n * the prompt is a best-effort optimisation; a model that does not read the\n * block, or whose question shares no words with it, can still ask. Ranking is\n * deterministic — no model involved — so recall does not depend on model\n * quality.\n */\n search(query: string, limit = 8): Array<{ item: MemoryItem; score: number }> {\n const q = relevanceTokens(query);\n if (q.size === 0) return [];\n\n const pool: MemoryItem[] = [\n ...this.l1HotCache.values(),\n ...this.l2WarmStore.values(),\n ...this.l3ColdArchive.values(),\n ];\n\n const scored = pool\n .map((item) => ({\n item,\n score: overlapScore(q, relevanceTokens(`${item.content} ${item.metadata.domains.join(\" \")}`)),\n }))\n .filter((entry) => entry.score > 0)\n .sort((a, b) => b.score - a.score || a.item.content.length - b.item.content.length);\n\n // Collapse paraphrases of the same fact to the best-scoring instance.\n const seen: string[] = [];\n const out: Array<{ item: MemoryItem; score: number }> = [];\n for (const entry of scored) {\n // Identical-on-identity-tokens, not identical-on-words: a paraphrase of one\n // fact should occupy one slot in a result list.\n if (seen.some((existing) => similarity(existing, entry.item.content) >= COLLAPSE_THRESHOLD)) {\n continue;\n }\n seen.push(entry.item.content);\n out.push(entry);\n if (out.length >= Math.max(1, limit)) break;\n }\n return out;\n }\n\n /**\n * Post-turn asynchronous execution.\n * Fired when the agent finishes streaming its response to the user.\n * Evaluates turn, manages L1 cache, detects tensions, updates self-model.\n */\n async postTurnAsync(params: {\n userMessage: string;\n assistantResponse: string;\n detectedDomains?: string[];\n }): Promise<void> {\n this.stats.totalTurnsProcessed += 1;\n\n // 1. Update active domains\n if (params.detectedDomains && params.detectedDomains.length > 0) {\n this.selfModel.activeDomains = Array.from(\n new Set([...this.selfModel.activeDomains, ...params.detectedDomains])\n );\n }\n\n // 2. Select candidates from L2 for Arbiter evaluation\n const candidates = Array.from(this.l2WarmStore.values())\n .slice(0, 20)\n .map((item) => ({\n id: item.id,\n bookmark: item.bookmark,\n domains: item.metadata.domains,\n hasTension: false,\n }));\n\n const l1Summaries = Array.from(this.l1HotCache.values()).map((m) => ({\n id: m.id,\n bookmark: m.bookmark,\n domains: m.metadata.domains,\n }));\n\n // 3. Run Arbiter if configured, or use built-in heuristic arbiter\n const evaluation = this.arbiter\n ? await this.arbiter({\n turnText: params.userMessage,\n assistantReply: params.assistantResponse,\n l0Prompt: this.activeTaskTrace,\n l1Summaries,\n candidates,\n })\n : this.runHeuristicArbiter(params, candidates);\n\n // 4. Apply Arbiter Decision\n this.applyArbiterDecision(evaluation);\n\n // 5. Learn from the turn. A model-backed extractor is preferred: the regex\n // fallback only catches \"always/never/remember to\", so plain project\n // facts (\"the staging URL is X\") were never learned at all.\n if (this.autoExtractMemories) {\n if (this.extract) {\n try {\n await this.applyExtraction(\n await this.extract({ userMessage: params.userMessage, assistantResponse: params.assistantResponse }),\n );\n } catch {\n // A failed extraction must not break the turn; the regex fallback below\n // still gets a chance.\n this.autoExtractTurnMemory(params.userMessage, params.assistantResponse);\n }\n } else if (params.assistantResponse.length > 50) {\n this.autoExtractTurnMemory(params.userMessage, params.assistantResponse);\n }\n }\n\n // 6. Enforce the L0/L1 budgets so the \"cache\" cannot grow without bound.\n this.enforceBudgets();\n\n // 7. Trigger persistence callback if registered\n if (this.onPersist) {\n try {\n await this.onPersist(this.getSnapshot());\n } catch {\n // Non-blocking\n }\n }\n }\n\n /**\n * Fold extracted memories and tensions in, skipping anything already known.\n *\n * Extracted items land in L2 rather than L1: they are candidates, and the\n * arbiter decides what is worth pre-staging. That is what gives the tiering\n * something to actually do — previously nothing ever wrote to L2, so every\n * arbiter run evaluated an empty candidate set.\n */\n private async applyExtraction(result: {\n memories: Array<{ content: string; domains?: string[] }>;\n tensions?: Array<{\n claimA: string;\n claimB: string;\n impact: \"low\" | \"medium\" | \"critical\";\n actionableQuestion: string;\n }>;\n }): Promise<void> {\n // Memories held aside for one batched adjudication at the end of the turn.\n const pending: Array<{ content: string; candidates: MemoryItem[] }> = [];\n for (const memory of result.memories ?? []) {\n const content = memory.content.trim();\n if (content.length < 8 || content.length > 600) continue;\n if (isInteractionScoped(content)) continue;\n\n // Two stages: recall candidates cheaply, then adjudicate.\n //\n // The safe default when nothing can adjudicate, or when the adjudicator is\n // unsure, is to add. An unmerged duplicate costs one row; a wrong merge\n // corrupts what we believe and is hard to unwind. Zep publishes the same\n // bias: prefer under-merge over over-merge.\n let stored = content;\n const candidates = this.recallSimilar(content);\n if (candidates.length > 0) {\n let verdict: MemoryReconciliation = { action: \"add\" };\n if (this.reconcile) {\n // Deferred: one adjudicator call for the whole turn, not one per\n // memory. Awaiting inside this loop made a five-memory turn cost six\n // serial model calls.\n // Added optimistically below, then the batch verdict may reject,\n // merge or replace it. Storing first keeps memory available even if\n // the adjudicator is slow or never answers.\n pending.push({ content, candidates });\n } else if (candidates.some((c) => c.content.trim().toLowerCase() === content.trim().toLowerCase())) {\n // Byte-identical restatement: never worth storing twice.\n verdict = { action: \"merge\" };\n }\n\n if (verdict.action === \"reject\") continue;\n if (verdict.action === \"merge\") {\n // Merge means one memory survives, holding the fuller statement -\n // never \"keep both\" and never \"keep the barer one\". A rewrite that\n // would drop information is declined, and falling through stores the\n // restatement separately instead of losing what it added.\n // The incoming statement was never stored, so there is nothing to\n // remove: it folds into the survivor or falls through and is kept.\n if (candidates[0] && this.mergeInto(candidates[0], verdict.content, { text: content, stored: false })) {\n continue;\n }\n }\n if (verdict.action === \"replace\") {\n // Supersede rather than keep both: the old entry stops being returned.\n this.supersede(candidates.map((c) => c.content));\n }\n stored = verdict.content?.trim() || content;\n }\n\n const now = Date.now();\n const id = `mem-${now}-${Math.random().toString(36).slice(2, 7)}`;\n // File it in L1, not L2. The user stated this one turn ago, so it is\n // relevant by definition: waiting for the arbiter to promote it added a\n // one-turn lag, which meant a freshly-taught fact was still missing from\n // the very next prompt.\n this.addMemory(\n {\n id,\n content: stored,\n bookmark: stored.slice(0, 80),\n tier: \"L1\",\n metadata: {\n domains: memory.domains ?? [],\n createdAt: now,\n lastAccessedAt: now,\n accessCount: 1,\n },\n },\n \"L1\",\n );\n }\n\n // One adjudicator call for the whole turn. Failures fall back to \"keep\n // both\", so a flaky model costs duplicates, never lost information.\n if (pending.length > 0 && this.reconcile) {\n let verdicts: MemoryReconciliation[] = [];\n try {\n verdicts = await this.reconcile({\n items: pending.map((p) => ({ candidate: p.content, remember: p.candidates.map((c) => c.content) })),\n });\n } catch {\n verdicts = [];\n }\n for (const [index, entry] of pending.entries()) {\n const verdict = verdicts[index];\n if (!verdict) continue;\n if (verdict.action === \"reject\") this.removeByContent(entry.content);\n else if (verdict.action === \"merge\") {\n const survivor = entry.candidates[0];\n // Stored optimistically, so the duplicate is removed on the way in -\n // before the rewrite, never after.\n if (survivor && this.mergeInto(survivor, verdict.content, { text: entry.content, stored: true })) {\n continue;\n }\n } else if (verdict.action === \"replace\") {\n this.supersede(entry.candidates.map((c) => c.content));\n if (verdict.content) this.replaceByContent(entry.content, verdict.content);\n }\n }\n }\n\n for (const tension of result.tensions ?? []) {\n const key = `${tension.claimA}::${tension.claimB}`.toLowerCase();\n if (this.activeTensions.has(key)) continue;\n this.addTension({\n id: key,\n status: \"active\",\n claimA: { source: \"user\", statement: tension.claimA, timestamp: Date.now() },\n claimB: { source: \"conversation\", statement: tension.claimB, timestamp: Date.now() },\n impact: tension.impact,\n taskRelevance: 1,\n actionableQuestion: tension.actionableQuestion,\n });\n }\n }\n\n /** Drop an entry by its exact content. */\n private removeByContent(content: string): void {\n const target = content.trim().toLowerCase();\n for (const map of [this.l1HotCache, this.l2WarmStore, this.l3ColdArchive]) {\n for (const [id, item] of map) {\n if (item.content.trim().toLowerCase() === target) map.delete(id);\n }\n }\n }\n\n /** Rewrite one entry's text in place, matched on its old value. */\n private replaceByContent(from: string, to: string): void {\n const target = from.trim().toLowerCase();\n for (const map of [this.l1HotCache, this.l2WarmStore, this.l3ColdArchive]) {\n for (const item of map.values()) {\n if (item.content.trim().toLowerCase() === target && !isLossyRewrite(item.content, to)) {\n this.enrich(item, to);\n }\n }\n }\n }\n\n /** Replace an entry's content, keeping its identity and tags. */\n private enrich(target: MemoryItem, content: string): void {\n target.content = content;\n target.bookmark = content.slice(0, 80);\n target.metadata.lastAccessedAt = Date.now();\n }\n\n /**\n * Fold a duplicate into its survivor, refusing rewrites that drop anything.\n *\n * `merge` returns the model's idea of the fuller statement, and overwriting\n * with it deletes whatever the model happened to leave out. The under-merge\n * bias covers merging the *wrong* pair, but nothing covered a lossy rewrite\n * of the right pair, so containment is checked first.\n *\n * @returns false when the rewrite would lose information, in which case the\n * caller keeps both entries.\n */\n private mergeInto(\n survivor: MemoryItem,\n replacement: string | undefined,\n duplicate: { text: string; stored: boolean },\n ): boolean {\n const text = replacement?.trim();\n // Both statements are checked, not just the survivor: a merge has to carry\n // everything either one held, so dropping the *incoming* qualifier loses it\n // just as permanently as dropping the survivor's.\n if (\n text &&\n (isLossyRewrite(survivor.content, text) || isLossyRewrite(duplicate.text, text))\n ) {\n return false;\n }\n // Remove the duplicate BEFORE rewriting the survivor: afterwards the two\n // hold the same text, so removing by content would match both.\n if (duplicate.stored) this.removeByContent(duplicate.text);\n if (text) this.enrich(survivor, text);\n return true;\n }\n\n /** Retire the entries a replacement supersedes, keeping them out of retrieval. */\n private supersede(contents: string[]): void {\n const targets = new Set(contents.map((c) => c.trim().toLowerCase()));\n for (const map of [this.l1HotCache, this.l2WarmStore, this.l3ColdArchive]) {\n for (const [id, item] of map) {\n if (targets.has(item.content.trim().toLowerCase())) map.delete(id);\n }\n }\n }\n\n /**\n * Existing memories worth adjudicating a candidate against.\n *\n * Cheap and deliberately over-inclusive. An identical string short-circuits\n * because it is never worth a model call; anything else above the recall floor\n * is offered to the adjudicator, which decides.\n */\n private recallSimilar(content: string): MemoryItem[] {\n const needle = distinctiveTokens(content);\n if (needle.size === 0) return [];\n const existing = [\n ...this.l1HotCache.values(),\n ...this.l2WarmStore.values(),\n ...this.l3ColdArchive.values(),\n ];\n\n const scored = existing\n .map((item) => {\n const have = distinctiveTokens(item.content);\n let shared = 0;\n for (const word of needle) if (have.has(word)) shared += 1;\n return { item, exact: item.content.trim().toLowerCase() === content.trim().toLowerCase(), score: have.size ? shared / Math.min(needle.size, have.size) : 0 };\n })\n // An exact restatement is certain; the rest are merely candidates.\n .filter((entry) => entry.exact || entry.score >= CANDIDATE_FLOOR)\n .sort((a, b) => Number(b.exact) - Number(a.exact) || b.score - a.score);\n\n return scored.slice(0, MAX_CANDIDATES).map((entry) => entry.item);\n }\n\n /**\n * Keep the pinned tiers within budget.\n *\n * `maxL0Tokens`/`maxL1Tokens` were stored but never read, so L1 grew for the\n * lifetime of the process. Evict least-recently-accessed first, and demote to\n * L2 rather than dropping, so nothing is lost.\n */\n private enforceBudgets(): void {\n const trim = (map: Map<string, MemoryItem>, budget: number): void => {\n if (budget <= 0) return;\n let total = 0;\n for (const item of map.values()) total += item.content.length / 4;\n if (total <= budget) return;\n const ordered = [...map.values()].sort(\n (a, b) => a.metadata.lastAccessedAt - b.metadata.lastAccessedAt,\n );\n for (const item of ordered) {\n if (total <= budget) break;\n map.delete(item.id);\n total -= item.content.length / 4;\n // Demote rather than discard: it can be promoted again later.\n this.l2WarmStore.set(item.id, { ...item, tier: \"L2\" });\n }\n };\n trim(this.l1HotCache, this.maxL1Tokens);\n }\n\n /**\n * Add a known tension manually or from an external source.\n */\n addTension(tension: KnowledgeTension): void {\n this.activeTensions.set(tension.id, tension);\n this.stats.tensionsDetected += 1;\n }\n\n /**\n * Mark a tension resolved with an optional reusable pattern.\n */\n resolveTension(id: string, resolution: { resolvedBy: string; pattern: string }): boolean {\n const t = this.activeTensions.get(id);\n if (!t) return false;\n t.status = \"resolved\";\n t.resolution = {\n resolvedAt: Date.now(),\n resolvedBy: resolution.resolvedBy,\n pattern: resolution.pattern,\n };\n return true;\n }\n\n /**\n * Add a memory directly to L2 warm storage or promote to L1.\n */\n addMemory(item: MemoryItem, targetTier: MemoryTier = \"L2\"): void {\n item.tier = targetTier;\n if (targetTier === \"L1\") {\n this.l1HotCache.set(item.id, item);\n } else if (targetTier === \"L2\") {\n this.l2WarmStore.set(item.id, item);\n } else if (targetTier === \"L3\") {\n this.l3ColdArchive.set(item.id, item);\n }\n }\n\n /**\n * Drop one memory by id, from whichever tier holds it.\n *\n * The counterpart to `addMemory`, and the only way to retire a fact that has\n * turned out to be wrong. One map is not enough to look in: a promotion or a\n * demotion moves an id between them, so an id that is absent from the hot\n * cache may still be in the warm store or the archive. Short-circuiting on the\n * first hit is therefore safe — an id lives in exactly one of the three.\n */\n removeMemory(id: string): boolean {\n return this.l1HotCache.delete(id) || this.l2WarmStore.delete(id) || this.l3ColdArchive.delete(id);\n }\n\n /**\n * Update the proprioceptive capability record for a domain.\n */\n recordDomainOutcome(domain: string, success: boolean, failurePattern?: string): void {\n const current = this.selfModel.domains[domain] ?? {\n reliabilityScore: 0.8,\n sampleCount: 0,\n knownFailurePatterns: [],\n recommendedStrategies: [],\n };\n\n const newSampleCount = current.sampleCount + 1;\n // Moving average update\n const weight = 1 / Math.min(newSampleCount, 10);\n const outcomeVal = success ? 1.0 : 0.0;\n const newScore = current.reliabilityScore * (1 - weight) + outcomeVal * weight;\n\n if (!success && failurePattern && !current.knownFailurePatterns.includes(failurePattern)) {\n current.knownFailurePatterns.push(failurePattern);\n }\n\n this.selfModel.domains[domain] = {\n reliabilityScore: Number(newScore.toFixed(3)),\n sampleCount: newSampleCount,\n knownFailurePatterns: current.knownFailurePatterns,\n recommendedStrategies: current.recommendedStrategies,\n };\n }\n\n getSnapshot(): CognitiveMemoryStateSnapshot {\n return {\n l0: {\n tensions: Array.from(this.activeTensions.values()),\n selfModel: JSON.parse(JSON.stringify(this.selfModel)),\n activeTaskTrace: this.activeTaskTrace,\n },\n l1: Array.from(this.l1HotCache.values()),\n l2: Array.from(this.l2WarmStore.values()),\n l3: Array.from(this.l3ColdArchive.values()),\n stats: { ...this.stats },\n };\n }\n\n loadSnapshot(snapshot: CognitiveMemoryStateSnapshot): void {\n this.activeTensions.clear();\n for (const t of snapshot.l0.tensions) {\n this.activeTensions.set(t.id, t);\n }\n this.selfModel = snapshot.l0.selfModel;\n this.activeTaskTrace = snapshot.l0.activeTaskTrace;\n\n this.l1HotCache.clear();\n for (const m of snapshot.l1) {\n this.l1HotCache.set(m.id, m);\n }\n\n this.l2WarmStore.clear();\n for (const m of snapshot.l2) {\n this.l2WarmStore.set(m.id, m);\n }\n\n this.l3ColdArchive.clear();\n for (const m of snapshot.l3) {\n this.l3ColdArchive.set(m.id, m);\n }\n\n this.stats = { ...snapshot.stats };\n }\n\n private applyArbiterDecision(evaluation: ArbiterEvaluationResult): void {\n // 1. Promotions to L1\n for (const p of evaluation.promotions) {\n const memory = this.l2WarmStore.get(p.memoryId) ?? this.l3ColdArchive.get(p.memoryId);\n if (memory) {\n memory.tier = \"L1\";\n memory.metadata.lastAccessedAt = Date.now();\n memory.metadata.accessCount += 1;\n this.l1HotCache.set(memory.id, memory);\n this.l2WarmStore.delete(memory.id);\n this.l3ColdArchive.delete(memory.id);\n }\n }\n\n // 2. Demotions to L2\n for (const d of evaluation.demotions) {\n const memory = this.l1HotCache.get(d.memoryId);\n if (memory) {\n memory.tier = \"L2\";\n this.l2WarmStore.set(memory.id, memory);\n this.l1HotCache.delete(memory.id);\n }\n }\n\n // 3. New Tensions\n for (const t of evaluation.detectedTensions) {\n const tensionId = `tension-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;\n this.addTension({\n id: tensionId,\n status: \"active\",\n claimA: { source: \"current conversation\", statement: t.claimA, timestamp: Date.now() },\n claimB: { source: \"known state / files\", statement: t.claimB, timestamp: Date.now() },\n impact: t.impact,\n taskRelevance: 1.0,\n actionableQuestion: t.actionableQuestion,\n });\n }\n\n // 4. Self-Model Updates\n if (evaluation.selfModelUpdate) {\n const { domain, success, failurePatternObserved } = evaluation.selfModelUpdate;\n if (success !== undefined) {\n this.recordDomainOutcome(domain, success, failurePatternObserved);\n }\n }\n }\n\n /**\n * Fast default heuristic arbiter when an LLM arbiter model is not supplied.\n */\n private runHeuristicArbiter(\n params: { userMessage: string; assistantResponse: string },\n candidates: Array<{ id: string; bookmark: string; domains: string[] }>\n ): ArbiterEvaluationResult {\n const promotions: ArbiterEvaluationResult[\"promotions\"] = [];\n const demotions: ArbiterEvaluationResult[\"demotions\"] = [];\n\n const turn = relevanceTokens(`${params.userMessage} ${params.assistantResponse}`);\n const scored = candidates\n .map((candidate) => ({\n candidate,\n score: overlapScore(\n turn,\n relevanceTokens(`${candidate.bookmark} ${candidate.domains.join(\" \")}`),\n ),\n }))\n .filter((entry) => entry.score > PROMOTE_THRESHOLD)\n .sort((a, b) => b.score - a.score)\n .slice(0, 3);\n\n for (const { candidate, score } of scored) {\n promotions.push({\n memoryId: candidate.id,\n targetTier: \"L1\",\n signalType: \"anticipatory\",\n urgency: Math.min(1, score),\n });\n }\n\n for (const item of this.l1HotCache.values()) {\n const relevant =\n overlapScore(turn, relevanceTokens(`${item.bookmark} ${item.metadata.domains.join(\" \")}`)) > 0;\n if (!relevant && this.l1HotCache.size > DEMOTE_ABOVE) {\n demotions.push({\n memoryId: item.id,\n targetTier: \"L2\",\n reason: \"Not referenced in recent turns\",\n });\n }\n }\n\n if (process.env.NAH_MEMORY_DEBUG) {\n console.log(\n ` [arbiter] scored=${JSON.stringify(scored.map((e) => ({ id: e.candidate.id, score: Number(e.score.toFixed(2)) })))} promotions=${promotions.length} demotions=${demotions.length}`,\n );\n }\n\n return { promotions, demotions, pins: [], detectedTensions: [] };\n }\n\n private autoExtractTurnMemory(userMsg: string, assistantReply: string): void {\n // If user provided a critical rule or config preference, store as warm memory\n const preferenceMatch = userMsg.match(/(?:always|never|make sure to|remember to|use)\\s+([^\\.\\n]+)/i);\n if (preferenceMatch && preferenceMatch[1]) {\n const id = `mem-pref-${Date.now()}`;\n const statement = preferenceMatch[1].trim();\n if (isInteractionScoped(`User preference: ${statement}`)) return;\n this.addMemory({\n id,\n content: `User preference: ${statement}`,\n bookmark: `User preference: ${statement.slice(0, 80)}`,\n tier: \"L1\", // Pre-stage directly into hot cache\n metadata: {\n domains: this.selfModel.activeDomains,\n createdAt: Date.now(),\n lastAccessedAt: Date.now(),\n accessCount: 1,\n },\n }, \"L1\");\n }\n }\n}\n","/**\n * Deterministic fact extraction.\n *\n * A model extractor is good at judgement but it is still a model: it can\n * refuse, hedge, or return nothing, and a fact the user plainly stated then\n * never gets learned. Everything stated unambiguously is captured here with\n * plain pattern matching, and the model is layered on top for the subtler cases.\n *\n * Only high-confidence shapes are matched. Being wrong in this direction writes\n * a useless memory; being silent loses a real one, which is the worse failure.\n */\n\nconst URL = /\\bhttps?:\\/\\/[^\\s<>()[\\]\"'`]+/g\n\n/**\n * Positive requirements only.\n *\n * \"never X\" reads correctly as a requirement. \"do not X\" / \"don't X\" must NOT be\n * captured here: naively taking the object of a negation produces nonsense like\n * \"The user requires: verify it against the repo\" from \"do not verify it against\n * the repo\", which inverts the meaning.\n */\nconst REQUIREMENT =\n /\\b(always|never|must|should|make sure to|remember to)\\b[\\s:]+([^.?!\\n]{4,160})/gi\n\n/**\n * \"<subject> is <value>\".\n *\n * The value must NOT stop at the first `.`: that truncates\n * `internal-hbr-2291.pineapple.example` to `internal-hbr-2291` and then poisons\n * recall with the broken value. Stop at a period only when it ends a sentence.\n */\nconst ASSIGNMENT = /\\b([A-Za-z][\\w ()-]{2,60}?)\\s+(?:is|are)\\s+([^\\n?!]{3,200})/g\n\nconst CODEISH = /[A-Z0-9_./:-]/\n\nconst looksLikeValue = (value: string): boolean => {\n const trimmed = value.trim()\n if (trimmed.length < 3 || trimmed.length > 200) return false\n if (/^(not|nothing|unclear|unknown|the same|that|this|it)\\b/i.test(trimmed)) return false\n return CODEISH.test(trimmed)\n}\n\n/** Cut a captured clause back to its first complete sentence. */\nconst firstSentence = (value: string): string => {\n const match = /\\.(?=\\s+[A-Z(])/.exec(value)\n return match ? value.slice(0, match.index) : value\n}\n\nconst tidy = (value: string): string =>\n firstSentence(value)\n .replace(/\\s+/g, \" \")\n .replace(/^(?:that|the|a|an|it|this)\\s+/i, \"\")\n .replace(/[,;:\\s.。]+$/, \"\")\n .trim()\n\nexport interface DeterministicMemory {\n readonly content: string\n readonly domains: Array<string>\n}\n\n/**\n * Extract statements the user made that are worth remembering, without a model.\n */\nexport const extractDeterministic = (userMessage: string): Array<DeterministicMemory> => {\n const out: Array<DeterministicMemory> = []\n const push = (content: string): void => {\n const cleaned = tidy(content)\n if (cleaned.length < 8 || cleaned.length > 300) return\n if (/^(yes|no|ok|okay|sure|thanks|thank you|got it|noted)\\b/i.test(cleaned)) return\n if (out.some((existing) => existing.content.toLowerCase() === cleaned.toLowerCase())) return\n out.push({ content: cleaned, domains: [] })\n }\n\n // 1. URLs are unambiguous.\n for (const match of userMessage.match(URL) ?? []) {\n push(`User-provided URL: ${match}`)\n }\n\n // 2. Stated requirements, kept in the user's own words.\n // Paraphrasing flipped meaning once: \"Never force push\" became\n // \"The user requires: force push\" — the exact opposite instruction.\n for (const match of userMessage.matchAll(REQUIREMENT)) {\n const verb = (match[1] ?? \"\").toLowerCase()\n const body = tidy(match[2] ?? \"\")\n if (!body) continue\n push(`User requirement (${verb}): ${body}`)\n }\n\n // 3. \"X is Y\" where Y is identifier-shaped.\n for (const match of userMessage.matchAll(ASSIGNMENT)) {\n const subject = tidy(match[1] ?? \"\")\n const value = tidy(match[2] ?? \"\")\n if (!subject || !looksLikeValue(value)) continue\n push(`${subject} is ${value}`)\n }\n\n // The three passes overlap: \"Always run the canary pipeline for staging\" gets\n // caught as a requirement *and* as an assignment, and the assignment copy is\n // truncated mid-value. Two rows for one sentence is noise the engine then has\n // to reconcile later, so the contained one is dropped here instead.\n const deduped = out.filter(\n (candidate, index) =>\n !out.some((other, otherIndex) => {\n if (otherIndex === index) return false\n if (other.content.length <= candidate.content.length) return false\n return isCoveredBy(candidate.content, other.content)\n })\n )\n\n return deduped.slice(0, 6)\n}\n\n/**\n * Whether everything worth keeping in `narrow` is already in `wide`.\n *\n * Compared on the tokens that carry a fact's identity, so dropping a number or a\n * qualifier counts as loss even when the wording differs.\n */\nconst isCoveredBy = (narrow: string, wide: string): boolean => {\n const have = new Set(wide.toLowerCase().split(/[^a-z0-9]+/).filter((word) => word.length >= 4))\n const covered = narrow\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((word) => word.length >= 4)\n return covered.length > 0 && covered.every((word) => have.has(word))\n}\n"],"names":["CognitiveMemoryError","message","init","createHttpClient","config","apiKey","baseUrl","defaultBaseUrl","timeout","retry","debug","extraHeaders","inner","ofetch","options","request","response","error","FetchError","body","ContextResource","client","MemoriesResource","params","id","tier","RecallResource","SelfModelResource","StatsResource","fetchHealth","origin","TensionsResource","status","TurnsResource","Cogmem","createClient","runTurn","memory","input","context","assistantResponse","learning","recallOrExplain","query","lines","hit","domains","seedMemories","result","content","CONTRADICTION_PATTERNS","DOMAIN_KEYWORDS","runFastGate","userMessage","pattern","extractDomains","text","matched","domain","patterns","p","STOP_WORDS","FILLER_TOKENS","relevanceTokens","value","word","overlapScore","candidate","shared","CANDIDATE_FLOOR","PROMOTE_THRESHOLD","MAX_CANDIDATES","COLLAPSE_THRESHOLD","distinctiveTokens","w","isLossyRewrite","original","replacement","fold","tokens","t","after","token","HOSTNAME","NOT_A_HOSTNAME","extractIdentifiers","found","match","INTERACTION_SCOPED","isInteractionScoped","similarity","a","b","left","right","normalise","estimateTokens","gistOf","item","trimmed","DEMOTE_ABOVE","CognitiveMemory","force","sections","entries","used","truncated","include","reason","withBody","gist","tags","suffix","gate","weakDomains","d","x","capability","cap","indexLines","activeTensions","currentUserMessage","limit","q","scored","entry","seen","out","existing","candidates","l1Summaries","m","evaluation","pending","stored","verdict","c","now","verdicts","index","survivor","tension","key","target","map","from","to","duplicate","contents","targets","needle","have","budget","total","ordered","resolution","targetTier","success","failurePattern","current","newSampleCount","weight","outcomeVal","newScore","snapshot","tensionId","failurePatternObserved","promotions","demotions","turn","score","e","userMsg","assistantReply","preferenceMatch","statement","URL","REQUIREMENT","ASSIGNMENT","CODEISH","looksLikeValue","firstSentence","tidy","extractDeterministic","push","cleaned","verb","subject","other","otherIndex","isCoveredBy","narrow","wide","covered"],"mappings":"0GAcO,MAAMA,UAA6B,KAAM,CAO9C,OAAyB,KAAO,uBAGvB,KACA,OAEA,cAEA,OACA,KAET,YACEC,EACAC,EAOA,CACA,MAAMD,CAAO,EACb,KAAK,KAAO,uBACZ,KAAK,OAASC,EAAK,OACnB,KAAK,KAAOA,EAAK,KACjB,KAAK,KAAOA,EAAK,KACjB,KAAK,cAAgBA,EAAK,cAC1B,KAAK,OAASA,EAAK,OAGf,MAAM,mBACR,MAAM,kBAAkB,KAAMF,CAAoB,CAEtD,CAGA,aAAuB,CACrB,OAAO,KAAK,SAAW,GACzB,CAGA,cAAwB,CACtB,OAAO,KAAK,SAAW,GACzB,CAGA,mBAA6B,CAC3B,OAAO,KAAK,SAAW,GACzB,CAGA,iBAA2B,CACzB,OAAO,KAAK,SAAW,GACzB,CAEA,kBAA4B,CAC1B,OAAO,KAAK,SAAW,GACzB,CAGA,eAAyB,CACvB,OAAO,KAAK,QAAU,GACxB,CACF,CClEO,SAASG,EAAiBC,EAAuC,CACtE,KAAM,CACJ,OAAAC,EACA,QAAAC,EAAUC,EAAA,EACV,QAAAC,EAAU,IACV,MAAAC,EAAQ,EACR,MAAAC,EAAQ,GACR,QAASC,EAAe,CAAA,CAAC,EACvBP,EAEJ,GAAI,OAAOC,GAAW,UAAYA,EAAO,KAAA,IAAW,GAClD,MAAM,IAAI,MACR,mGAAA,EAIJ,MAAMO,EAAQC,EAAAA,OAAO,OAAO,CAC1B,QAAS,GAAGP,EAAQ,QAAQ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