🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

goodmemory

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

goodmemory - npm Package Compare versions

Comparing version
0.6.0
to
0.7.0
+4
dist/answer/evidenceLedgerContext.d.ts
import type { EvidenceLedgerEntry } from "../recall/evidenceLedger";
import { type LanguageService } from "../language";
export type EvidenceLedgerFormat = "prose" | "chronology" | "compact_json" | "json_locale_note";
export declare function renderEvidenceLedgerContext(entries: readonly EvidenceLedgerEntry[], format: EvidenceLedgerFormat, locale?: string, language?: LanguageService): string;
import{Xa as M,Ya as g,_a as x,ab as f,bb as v,fb as d,hb as p}from"./chunk-wy6fj8p6.js";import{SQL as u}from"bun";var m="public",s="gm",C="gm_documents",S="gm_session_state",r="gm_storage_schema",N="document_indexes",V=1,o=/^[A-Za-z_][A-Za-z0-9_]*$/,i=[{method:"btree",methodAndKey:"USING btree (collection)",name:"gm_documents_collection_idx"},{method:"gin",methodAndKey:"USING gin (document)",name:"gm_documents_document_gin_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'text'), '')))",name:"gm_documents_text_search_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'searchText'), '')))",name:"gm_documents_search_text_search_idx"}],b=new Map;function l(G){let J=G.trim();if(J.length===0)throw Error("Postgres storage requires a non-empty url");return J}function T(G,J){if(!o.test(G))throw Error(`Invalid Postgres ${J}: ${G}. Use only letters, digits, and underscores, and start with a letter or underscore.`);return G}function j(G){return`"${G}"`}function B(G,J){return`${j(G)}.${j(J)}`}function c(G){return JSON.stringify(G)}function D(G){return c(G)}function z(G){if(typeof G!=="string")return G;let J=JSON.parse(G);if(typeof J!=="string")return J;try{return JSON.parse(J)}catch{return J}}function n(G){return Boolean(G&&Object.keys(G).length>0)}function A(G,J,F){if(!n(J))return"";return F.push(D(J)),` AND ${G} @> $${F.length}::text::jsonb`}function t(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`{${G.join(",")}}`}function e(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`[${G.join(",")}]`}function k(G){let J=null;return async()=>{if(!J)J=G().catch((F)=>{throw J=null,F});await J}}function I(G){return Error(`Postgres ${G} store is read-only in this context.`)}async function y(G,J){let F=await G.unsafe("SELECT to_regclass($1)::text AS oid",[J]);return F[0]?.oid!==null&&F[0]?.oid!==void 0}function R(G){let J=l(G.url),F=T(G.schema??m,"schema"),O=T(G.vectorTablePrefix??s,"vectorTablePrefix"),H=`${O}_vectors`,U=c({url:J,schema:F,vectorTablePrefix:O}),Q=b.get(U);if(Q)return Q;let W=new u(J,{prepare:!1}),X=j(F),_=B(F,C),$=B(F,S),Y=B(F,H),K=`${F}.${C}`,Z=`${F}.${S}`,E=`${F}.${H}`,P=k(async()=>{await W.unsafe(`CREATE SCHEMA IF NOT EXISTS ${X}`)}),L={sql:W,schema:F,documentTable:_,sessionStateTable:$,vectorTable:Y,hasDocumentStore:()=>y(W,K),hasSessionStore:()=>y(W,Z),hasVectorStore:()=>y(W,E),ensureDocumentStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${_} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
document JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`)}),ensureSessionStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${$} (
scope_key TEXT NOT NULL,
state_kind TEXT NOT NULL,
payload JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_key, state_kind)
)
`)}),ensureVectorStore:k(async()=>{await P(),await W.unsafe("CREATE EXTENSION IF NOT EXISTS vector"),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${Y} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding DOUBLE PRECISION[] NOT NULL,
metadata JSONB NOT NULL,
content TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_collection_idx`)}
ON ${Y} (collection)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_metadata_gin_idx`)}
ON ${Y} USING GIN (metadata)
`)})};return b.set(U,L),L}function q(G,J,F){return{async set(O,H){if(F?.readOnly)throw I("session");await G.ensureSessionStore(),await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind)
DO UPDATE SET
payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
`,[M(O),J,D(H)])},async setIfUnchanged(O,H,U){if(F?.readOnly)throw I("session");await G.ensureSessionStore();let Q=M(O);return(H===null?await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind) DO NOTHING
RETURNING 1 AS count
`,[Q,J,D(U)]):await G.sql.unsafe(`
UPDATE ${G.sessionStateTable}
SET
payload = $3::text::jsonb,
updated_at = NOW()
WHERE scope_key = $1
AND state_kind = $2
AND payload = $4::text::jsonb
RETURNING 1 AS count
`,[Q,J,D(U),D(H)])).length===1},async get(O){if(F?.readOnly&&!await G.hasSessionStore())return null;if(!F?.readOnly)await G.ensureSessionStore();let U=(await G.sql.unsafe(`
SELECT payload::text AS payload_json
FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
`,[M(O),J]))[0];return U?z(U.payload_json):null},async deleteIfUnchanged(O,H){if(F?.readOnly)throw I("session");return await G.ensureSessionStore(),(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1
AND state_kind = $2
AND payload = $3::text::jsonb
RETURNING 1 AS count
`,[M(O),J,D(H)])).length===1},async deleteByScope(O){if(F?.readOnly)throw I("session");if(await G.ensureSessionStore(),O.sessionId!==void 0)return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
RETURNING 1 AS count
`,[M(O),J])).length;return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key LIKE $1 AND state_kind = $2
RETURNING 1 AS count
`,[`${g(O)}%`,J])).length}}}function XF(G,J){let F=R(G);return{projectionBatchSemantics:x,async set(O,H,U){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[O,H,D(U)])},async get(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return null;if(!J?.readOnly)await F.ensureDocumentStore();let Q=(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H]))[0];return Q?z(Q.document_json):null},async update(O,H,U){if(J?.readOnly)throw I("document");if(await F.ensureDocumentStore(),(await F.sql.unsafe(`
UPDATE ${F.documentTable}
SET
document = document || $3::text::jsonb,
updated_at = NOW()
WHERE collection = $1 AND id = $2
RETURNING id
`,[O,H,D(U)])).length===0)throw Error(`Document not found for update: ${O}/${H}`)},async query(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H,U);return(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
ORDER BY id ASC
`,U)).map((X)=>z(X.document_json))},async queryPage(O,H){if(f(H),J?.readOnly&&!await F.hasDocumentStore())return{items:[]};if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H.filter,U);U.push(H.cursor??null);let W=U.length;U.push(H.limit+1);let X=U.length,_=await F.sql.unsafe(`
SELECT id, document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
AND ($${W}::text IS NULL OR id > $${W})
ORDER BY id ASC
LIMIT $${X}
`,U),$=_.slice(0,H.limit);return{items:$.map((Y)=>z(Y.document_json)),..._.length>H.limit?{nextCursor:$.at(-1).id}:{}}},async searchText(O,H){if(v(H),d(H.query).length===0)return[];if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=p(H.query),Q=H.field==="text"?"to_tsvector('simple', COALESCE(document ->> 'text', ''))":H.field==="searchText"?"to_tsvector('simple', COALESCE(document ->> 'searchText', ''))":null;if(Q){let Z=[O,U.tsQuery],E=A("document",H.filter,Z);return Z.push(H.limit),(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
ts_rank(
${Q},
to_tsquery('simple', $2)
) AS score
FROM ${F.documentTable}
WHERE collection = $1${E}
AND ${Q} @@ to_tsquery('simple', $2)
ORDER BY score DESC, id ASC
LIMIT $${Z.length}
`,Z)).map((L)=>({document:z(L.document_json),id:L.id,score:Number(L.score)}))}let W=[O,H.field,U.tsQuery],X=A("document",H.filter,W),$=U.substrings.map((Z)=>{return W.push(Z),W.length}).map((Z)=>`lower(COALESCE(document ->> $2, '')) LIKE $${Z}`).join(" OR ");W.push(H.limit);let Y=W.length;return(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
GREATEST(
ts_rank(
to_tsvector('simple', COALESCE(document ->> $2, '')),
to_tsquery('simple', $3)
),
CASE
WHEN ${$}
THEN 0.1
ELSE 0
END
) AS score
FROM ${F.documentTable}
WHERE collection = $1${X}
AND (
to_tsvector('simple', COALESCE(document ->> $2, ''))
@@ to_tsquery('simple', $3)
OR ${$}
)
ORDER BY score DESC, id ASC
LIMIT $${Y}
`,W)).map((Z)=>({document:z(Z.document_json),id:Z.id,score:Number(Z.score)}))},async writeBatchIfUnchanged(O){if(J?.readOnly)throw I("document");return await F.ensureDocumentStore(),F.sql.begin(async(H)=>{for(let U of[O.expected,...O.unchanged??[]]){await H.unsafe("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",[U.collection,U.id]);let Q=U.document===null?await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
FOR UPDATE
`,[U.collection,U.id]):await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
AND document = $3::text::jsonb
FOR UPDATE
`,[U.collection,U.id,D(U.document)]);if(!(U.document===null?Q.length===0:Q.length===1))return!1}for(let U of O.set)await H.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[U.collection,U.id,D(U.document)]);for(let U of O.delete??[])await H.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[U.collection,U.id]);return!0})},async delete(O,H){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}function YF(G,J){let F=R(G),O=q(F,"buffer",J),H=q(F,"working_memory",J),U=q(F,"journal",J);return{saveBuffer(Q,W){return O.set(Q,W)},saveBufferIfUnchanged(Q,W,X){return O.setIfUnchanged(Q,W,X)},getBuffer(Q){return O.get(Q)},deleteBufferIfUnchanged(Q,W){return O.deleteIfUnchanged(Q,W)},deleteBuffersByScope(Q){return O.deleteByScope(Q)},saveWorkingMemory(Q,W){return H.set(Q,W)},getWorkingMemory(Q){return H.get(Q)},deleteWorkingMemoryByScope(Q){return H.deleteByScope(Q)},saveJournal(Q,W){return U.set(Q,W)},getJournal(Q){return U.get(Q)},deleteJournalsByScope(Q){return U.deleteByScope(Q)}}}function ZF(G,J){let F=R(G);return{async upsert(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.begin(async(U)=>{for(let Q of H)await U.unsafe(`
INSERT INTO ${F.vectorTable} (
collection,
id,
embedding,
metadata,
content,
updated_at
) VALUES (
$1,
$2,
$3::double precision[],
$4::text::jsonb,
$5,
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
embedding = EXCLUDED.embedding,
metadata = EXCLUDED.metadata,
content = EXCLUDED.content,
updated_at = EXCLUDED.updated_at
`,[O,Q.id,t(Q.embedding),D(Q.metadata),Q.content])})},async get(O,H){if(J?.readOnly&&!await F.hasVectorStore())return null;if(!J?.readOnly)await F.ensureVectorStore();let Q=(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
0 AS score
FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
LIMIT 1
`,[O,H]))[0];if(!Q)return null;return{id:Q.id,embedding:z(Q.embedding_json),metadata:z(Q.metadata_json),content:Q.content}},async search(O,H,U){if(U.topK<=0||H.length===0)return[];if(J?.readOnly&&!await F.hasVectorStore())return[];if(!J?.readOnly)await F.ensureVectorStore();let Q=[O],W=A("metadata",U.filter,Q);Q.push(e(H));let X=Q.length;Q.push(U.topK);let _=Q.length;return(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
((embedding::vector <#> $${X}::vector) * -1) AS score
FROM ${F.vectorTable}
WHERE collection = $1${W}
ORDER BY embedding::vector <#> $${X}::vector ASC, id ASC
LIMIT $${_}
`,Q)).map((Y)=>({id:Y.id,embedding:z(Y.embedding_json),metadata:z(Y.metadata_json),content:Y.content,score:Number(Y.score)}))},async delete(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.unsafe(`
DELETE FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}async function a(G){let F=await R(G).sql.unsafe(`
SELECT
EXISTS (
SELECT 1
FROM pg_extension
WHERE extname = 'vector'
) AS installed,
EXISTS (
SELECT 1
FROM pg_available_extensions
WHERE name = 'vector'
) AS available
`);if(F[0]?.installed)return"installed";if(F[0]?.available)return"available";return"missing"}function FF(G){let J=B(G.schema,r);return{async runExclusive(F){let O=await G.sql.reserve(),H=["goodmemory",G.schema,N].join(":");try{return await O.unsafe("SELECT pg_advisory_lock(hashtextextended($1, 0))",[H]),await F()}finally{try{await O.unsafe("SELECT pg_advisory_unlock(hashtextextended($1, 0))",[H])}finally{O.release()}}},async createDocumentIndex(F){await G.sql.unsafe(F)},ensureDocumentStore:G.ensureDocumentStore,async ensureVersionStore(){await G.sql.unsafe(`
CREATE TABLE IF NOT EXISTS ${J} (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`)},async getDocumentIndex(F){let H=(await G.sql.unsafe(`
SELECT
pg_get_indexdef(index_relation.oid) AS definition,
index_metadata.indpred IS NOT NULL AS is_partial,
index_metadata.indisready AS is_ready,
index_metadata.indisunique AS is_unique,
index_metadata.indisvalid AS is_valid,
access_method.amname AS method,
table_relation.relname AS table_name,
table_namespace.nspname AS table_schema
FROM pg_class AS index_relation
JOIN pg_namespace AS index_namespace
ON index_namespace.oid = index_relation.relnamespace
JOIN pg_index AS index_metadata
ON index_metadata.indexrelid = index_relation.oid
JOIN pg_class AS table_relation
ON table_relation.oid = index_metadata.indrelid
JOIN pg_namespace AS table_namespace
ON table_namespace.oid = table_relation.relnamespace
JOIN pg_am AS access_method
ON access_method.oid = index_relation.relam
WHERE index_namespace.nspname = $1
AND index_relation.relname = $2
`,[G.schema,F]))[0];return H?{definition:H.definition,isPartial:H.is_partial,isReady:H.is_ready,isUnique:H.is_unique,isValid:H.is_valid,method:H.method,tableName:H.table_name,tableSchema:H.table_schema}:null},async getVersion(){return(await G.sql.unsafe(`
SELECT version
FROM ${J}
WHERE component = $1
`,[N]))[0]?.version??null},async setVersion(F){await G.sql.unsafe(`
INSERT INTO ${J} AS storage_schema (
component,
version,
updated_at
)
VALUES ($1, $2, NOW())
ON CONFLICT (component)
DO UPDATE SET
version = GREATEST(storage_schema.version, EXCLUDED.version),
updated_at = EXCLUDED.updated_at
`,[N,F])}}}function w(G){let J=G.toLocaleLowerCase("en-US"),F=J.startsWith("using ")?0:J.indexOf(" using ");if(F<0)return"";let O=G.slice(F),H=!1,U="";for(let Q=0;Q<O.length;Q+=1){let W=O[Q];if(W==="'"){if(U+=W,H&&O[Q+1]==="'")U+="'",Q+=1;else H=!H;continue}if(H){U+=W;continue}let X=O.slice(Q).toLocaleLowerCase("en-US"),_=["::regconfig","::text"].find(($)=>X.startsWith($));if(_){Q+=_.length-1;continue}if(W==='"'||/\s/.test(W))continue;U+=W.toLocaleLowerCase("en-US")}return U}function h(G,J,F){if(!(F!==null&&F.isValid&&F.isReady&&!F.isUnique&&!F.isPartial&&F.method.toLocaleLowerCase("en-US")===J.method&&F.tableName===C&&F.tableSchema===G&&w(F.definition)===w(J.methodAndKey)))throw Error(`Postgres document index ${G}.${J.name} exists but is invalid or has an unexpected definition. Drop it with DROP INDEX CONCURRENTLY and rerun the migration.`)}function GF(G){console.error(`[GoodMemory Postgres migration] status=${G.status} schema=${G.schema} index=${G.index} elapsedMs=${G.elapsedMs}`)}async function _F(G,J,F){l(G.url);let O=T(G.schema??m,"schema"),H=F?.port??FF(R(G)),U=J?.log??GF;await H.runExclusive(async()=>{await H.ensureDocumentStore(),await H.ensureVersionStore();let Q=await H.getVersion();if(Q!==null&&Q>V)throw Error(`Postgres document index schema ${O} has unsupported version ${Q}.`);for(let W of i){let X=await H.getDocumentIndex(W.name);if(X){h(O,W,X),U({elapsedMs:0,index:W.name,schema:O,status:"current"});continue}let _=Date.now();U({elapsedMs:0,index:W.name,schema:O,status:"creating"}),await H.createDocumentIndex(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${j(W.name)} ON ${B(O,C)} ${W.methodAndKey}`);let $=await H.getDocumentIndex(W.name);h(O,W,$),U({elapsedMs:Date.now()-_,index:W.name,schema:O,status:"created"})}if(Q!==V)await H.setVersion(V)})}async function HF(G){let J=R(G);await J.ensureDocumentStore(),await J.ensureSessionStore(),await J.ensureVectorStore()}async function JF(G){let J=R(G),[F,O,H]=await Promise.all([J.hasDocumentStore(),J.hasSessionStore(),J.hasVectorStore()]);return F&&O&&H}async function $F(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.hasExistingStorageBackend??JF,H=await F(G);if(H==="missing")return"unusable";if(H!=="installed")return"inconclusive";return await O(G)?"readable":"inconclusive"}async function DF(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.ensureStorageBackend??HF;if(await F(G)==="missing")return!1;return await O(G),!0}export{$F as probeReadOnlyPostgresStorageBackend,_F as migratePostgresStorageBackend,a as getPostgresVectorExtensionStatus,HF as ensurePostgresStorageBackend,ZF as createPostgresVectorStore,YF as createPostgresSessionStore,XF as createPostgresDocumentStore,DF as canBootstrapPostgresStorageBackend};
export{XF as Ma,YF as Na,ZF as Oa,$F as Pa,DF as Qa};

Sorry, the diff of this file is too big to display

import{readFileSync as W}from"node:fs";var X=new URL("../../package.json",import.meta.url),Q;function Y(){if(Q)return Q;let z=JSON.parse(W(X,"utf8")),x=z.goodmemoryRelease;if(typeof z.version!=="string"||z.version.length===0||typeof x?.installCommandsApplyAfterPublish!=="boolean"||typeof x.npmDistTag!=="string"||x.npmDistTag.length===0||x.status!=="release-candidate"&&x.status!=="stable")throw Error("Unable to read GoodMemory package release metadata.");return Q={goodmemoryRelease:{installCommandsApplyAfterPublish:x.installCommandsApplyAfterPublish,npmDistTag:x.npmDistTag,status:x.status},version:z.version},Q}var q="https://github.com/hjqcan/GoodMemory",V="https://goodmemory.vibenest.net";function $(z={}){let x=z.packageMetadata??Y(),I=z.version??x.version;return{schemaVersion:"goodmemory.capability/v2",name:"goodmemory",version:I,kind:"memory-layer",summary:"Durable user/project memory layer for chat apps, copilots, and coding agents.",description:"GoodMemory is the product memory layer between an app or installed agent host and the model runtime: write selected facts, recall the right context, inject it into the next turn, audit what happened, and delete it when it is wrong.",notA:["llm","agent-framework","vector-database","rag-system"],license:"MIT",homepage:`${q}#readme`,repository:q,documentation:{inspector:`${q}/blob/main/docs/GoodMemory-Inspector-and-Admin-API.md`,llmsTxt:`${q}/blob/main/llms.txt`,readme:`${q}#readme`,quickstart:`${q}#quickstart-codex-or-claude-code-memory`},install:{npmGlobal:`npm install -g goodmemory@${I}`,npmPackage:`npm install goodmemory@${I}`,bun:`bun add goodmemory@${I}`},releaseStatus:{...x.goodmemoryRelease,tarball:`goodmemory-${I}.tgz`},memoryApi:["remember","recall","buildContext","feedback","forget","exportMemory","deleteAllMemory"],onboarding:[{audience:"installed-coding-agent-host",when:"You are, or run inside, Claude Code or Codex.",method:"cli",steps:[`npm install -g goodmemory@${I}`,"goodmemory setup","goodmemory status"],autoDetect:"goodmemory adopt",docs:`${q}#quickstart-codex-or-claude-code-memory`},{audience:"mcp-client",when:"You speak the Model Context Protocol (Cursor, Windsurf, Cline, Claude Desktop, Gemini CLI, OpenCode, or a custom MCP client).",method:"mcp",mcpServer:{command:"goodmemory-mcp",args:["--standalone","--user-id","YOUR_USER_ID"]},autoDetect:"goodmemory adopt",docs:`${q}#standalone-mcp-for-any-client`},{audience:"framework-agent-or-backend",when:"You are a framework agent (LangGraph, custom loop) or a backend that calls memory as an HTTP service.",method:"http",endpoint:V,selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",pythonClient:"pip install goodmemory-client",docs:`${q}#pythonfastapi-http-bridge`}],mcp:{command:"goodmemory-mcp",standaloneArgs:["--standalone","--user-id","YOUR_USER_ID"],primaryTools:["goodmemory_get_context","goodmemory_remember"],readOnlyToolCount:8,writeTool:"goodmemory_remember (opt-in via --allow-write)",registryName:"io.github.hjqcan/goodmemory",docs:`${q}#standalone-mcp-for-any-client`},http:{hosted:V,liveness:`${V}/healthz`,wellKnown:`${V}/.well-known/goodmemory.json`,auth:"bearer-token",selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",endpoints:{recall:"POST /memory/recall-context",remember:"POST /memory/remember",feedback:"POST /memory/feedback",export:"POST /memory/export",forget:"POST /memory/forget",revise:"POST /memory/revise"},pythonClient:"goodmemory-client (PyPI)",docs:`${q}#pythonfastapi-http-bridge`},benchmarks:{currentClaims:[],historicalEvidence:{url:`${q}/tree/main/benchmark-claims`,note:`The v0.6.0 LoCoMo, BEAM, and MemoryAgentBench results, plus older LongMemEval and ImplicitMemBench runs, remain reproducible versioned evidence. None is a current ${I} production claim until rerun against this package line. LongMemEval and ImplicitMemBench remain internal evidence.`}},capabilities:{localFirst:!0,embeddingFreeDefault:!0,builtInLanguagePacks:["en","zh-Hans","zh-Hant","ja","ko","fr","es"],durableStore:"sqlite (default), postgres (opt-in)",audit:!0,deletion:!0,localInspector:"goodmemory inspector serve (loopback-only React console and /admin/v1 API)",correctByDefaultRecall:"Recall never silently degrades: a downgraded strategy carries routing.warnings (semantic_recall_inactive) and routing.warningMessages (semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET) instead of quietly returning the lexical floor."},canonicalSources:{prose:`${q}#readme`,benchmarks:`${q}/tree/main/benchmark-claims`,note:"Benchmark entries keep explicit measuredPackageVersion provenance; a package version bump never relabels historical results. Source declarations remain in benchmark-claims/*.json."}}}
export{$ as a};
import{Xa as b,Ya as QG,_a as DG,ab as qG,bb as kG,cb as CG,db as YG,eb as EG,fb as PG,gb as RG,ib as ZG}from"./chunk-wy6fj8p6.js";import{Database as VG}from"bun:sqlite";import{Buffer as bG}from"node:buffer";import{mkdirSync as pG}from"node:fs";import{dirname as uG}from"node:path";import{spawnSync as NG}from"node:child_process";import{existsSync as yG}from"node:fs";import*as wG from"sqlite-vss";var t="vss_inner_product",HG=Symbol.for("goodmemory.sqlite.library-registry"),SG=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/usr/lib/x86_64-linux-gnu/libsqlite3.so","/usr/lib/aarch64-linux-gnu/libsqlite3.so","/usr/lib64/libsqlite3.so","/usr/lib/libsqlite3.so"],gG=`
import { Database } from "bun:sqlite";
const [customLibraryPath, vectorPath, vssPath] = process.argv.slice(1);
if (!customLibraryPath || !vectorPath || !vssPath) {
throw new Error("Missing sqlite-vss probe paths.");
}
Database.setCustomSQLite(customLibraryPath);
const database = new Database(":memory:", { strict: true });
try {
database.loadExtension(vectorPath);
database.loadExtension(vssPath);
database.query("select vss_version() as version").get();
database.exec(
"CREATE VIRTUAL TABLE __goodmemory_vss_probe USING vss0(embedding(3)); DROP TABLE __goodmemory_vss_probe;",
);
} finally {
database.close();
}
`;function m(G){if(!G)return;let Y=G.trim();return Y.length>0?Y:void 0}function fG(G){let Y=m(G);if(!Y)return[];return Y.split(",").map((Z)=>Z.trim()).filter((Z)=>Z.length>0)}function xG(G){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(G))throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION: ${G}. Expected a valid SQLite function identifier.`);return G}function vG(G){let Y=m(G);if(!Y)return;if(Y==="off"||Y==="prefer"||Y==="require")return Y;throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_MODE: ${Y}. Expected off|prefer|require.`)}function a(G){let{backend:Y,customLibraryPath:Z,entryPoint:H,mode:X,path:F,paths:W,searchFunction:A}=G;return{customLibraryPath:Z,vectorExtension:{backend:Y,entryPoint:H,mode:X,path:F,paths:W,searchFunction:A}}}function JG(G){return{config:a({backend:"none",customLibraryPath:G.customLibraryPath,entryPoint:void 0,mode:"off",path:void 0,paths:[],searchFunction:G.searchFunction}),diagnostics:{available:G.source==="disabled",backend:"none",effectiveMode:"off",reason:G.reason,requestedMode:G.requestedMode,source:G.source}}}function hG(G){let Y=NG(process.execPath,["-e",gG,"--",G.customLibraryPath,...G.paths],{encoding:"utf8",timeout:1e4});if(Y.error)return{loadable:!1,reason:Y.error.message};if(Y.status!==0)return{loadable:!1,reason:`${Y.stdout}${Y.stderr}`.trim()||`sqlite-vss probe exited with status ${Y.status}`};return{loadable:!0}}function mG(G={}){let Y=G.exists??yG,Z=(G.libraryCandidatePaths??SG).find((H)=>Y(H));if(!Z)return{runtime:null};try{let H=wG,X=Object.hasOwn(G,"getVectorLoadablePath")?G.getVectorLoadablePath:H.getVectorLoadablePath,F=Object.hasOwn(G,"getVssLoadablePath")?G.getVssLoadablePath:H.getVssLoadablePath;if(!X||!F)return{runtime:null};let W=X(),A=F();if(!Y(W)||!Y(A))return{runtime:null};let M={customLibraryPath:Z,paths:[W,A]},E=(G.probeRuntime??hG)(M);if(!E.loadable)return{runtime:null,unavailableReason:E.reason??"Bundled sqlite-vss runtime probe failed."};return{runtime:M}}catch(H){return{runtime:null,unavailableReason:`Failed to inspect bundled sqlite-vss runtime: ${H instanceof Error?H.message:String(H)}`}}}function jG(G=process.env,Y){let Z=m(G.GOODMEMORY_SQLITE_CUSTOM_LIBRARY_PATH),H=m(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),X=fG(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),F=vG(G.GOODMEMORY_SQLITE_VECTOR_MODE),W=xG(m(G.GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION)??t),A=m(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_ENTRYPOINT),M=Y?.inspectBundledSQLiteVssRuntime?Y.inspectBundledSQLiteVssRuntime():Y?.detectBundledSQLiteVssRuntime?{runtime:Y.detectBundledSQLiteVssRuntime()}:mG(),E=M.runtime,P=M.unavailableReason,U=F??(X.length>0||E||P?"prefer":"off");if(U==="off")return JG({customLibraryPath:Z,requestedMode:U,searchFunction:W,source:"disabled"});if(X.length>0)return{config:a({backend:"sql-function",customLibraryPath:Z,entryPoint:A,mode:U,path:H,paths:X,searchFunction:W}),diagnostics:{available:!0,backend:"sql-function",effectiveMode:U,requestedMode:U,source:"env"}};if(E){let Q=U==="require"?"require":"prefer";return{config:a({backend:"sqlite-vss",customLibraryPath:Z??E.customLibraryPath,entryPoint:A,mode:Q,path:E.paths.join(","),paths:E.paths,searchFunction:W}),diagnostics:{available:!0,backend:"sqlite-vss",effectiveMode:Q,requestedMode:U,source:"bundled-sqlite-vss"}}}return JG({customLibraryPath:Z,requestedMode:U,searchFunction:W,source:"unavailable",reason:P??"SQLite vector acceleration was requested, but no supported sqlite-vss runtime assets were detected and no manual GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH was configured."})}function BG(G,Y){if(!G.customLibraryPath)return;let Z=globalThis,H=Z[HG]??{configuredPaths:new WeakMap};Z[HG]=H;let X=H.configuredPaths.get(Y);if(X===G.customLibraryPath)return;if(X)throw Error(`SQLite runtime already uses ${X} and cannot switch to ${G.customLibraryPath}.`);Y.setCustomSQLite(G.customLibraryPath),H.configuredPaths.set(Y,G.customLibraryPath)}function AG(G,Y){if(G.mode==="off"||!(G.paths?.length??0))return{loaded:!1,reason:"SQLite vector acceleration is disabled."};try{for(let Z of G.paths)Y.loadExtension(Z,G.entryPoint);return{loaded:!0}}catch(Z){let H=Z instanceof Error?Z.message:String(Z);if(G.mode==="prefer")return{loaded:!1,reason:`Failed to load SQLite vector extension at ${G.path}: ${H}`};throw Error(`Failed to load SQLite vector extension at ${G.path}: ${H}`)}}var o=null,e=null,OG="document_filter_indexes",UG="document_text_fts_keys",zG=2,_G=2;function rG(){if(!o)o={customLibraryPath:TG().config.customLibraryPath},BG(o,VG);return o}function TG(){if(!e)e=jG();return e}function cG(G,Y){if(Y?.readOnly||G===":memory:")return;pG(uG(G),{recursive:!0})}function $G(G,Y){return rG(),cG(G,Y),new VG(G,{create:Y?.readOnly?!1:!0,readonly:Y?.readOnly??!1,strict:!0})}function dG(G){G.exec(`
CREATE TABLE IF NOT EXISTS documents (
collection TEXT NOT NULL,
id TEXT NOT NULL,
json TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE VIRTUAL TABLE IF NOT EXISTS document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TABLE IF NOT EXISTS document_text_fts_keys (
rowid INTEGER PRIMARY KEY,
collection TEXT NOT NULL,
id TEXT NOT NULL,
UNIQUE (collection, id)
);
CREATE TABLE IF NOT EXISTS document_store_schema (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL
);
`);try{G.exec("BEGIN IMMEDIATE");let Y=G.query("SELECT version FROM document_store_schema WHERE component = ?1");if(Y.get(UG)?.version!==zG)G.exec(`
DROP TABLE document_text_fts;
CREATE VIRTUAL TABLE document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
DELETE FROM document_text_fts_keys;
INSERT INTO document_text_fts_keys (collection, id)
SELECT collection, id
FROM documents
WHERE CASE WHEN json_valid(json)
THEN json_type(json, '$.text') = 'text' OR
json_type(json, '$.searchText') = 'text'
ELSE 0
END;
INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
SELECT keys.rowid, documents.collection, documents.id,
CASE WHEN json_type(documents.json, '$.text') = 'text'
THEN json_extract(documents.json, '$.text')
END,
CASE WHEN json_type(documents.json, '$.searchText') = 'text'
THEN json_extract(documents.json, '$.searchText')
END
FROM documents
JOIN document_text_fts_keys AS keys
ON keys.collection = documents.collection AND keys.id = documents.id;
`),G.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(UG,zG);if(Y.get(OG)?.version!==_G)G.exec(`
DROP INDEX IF EXISTS documents_collection_scope_key_idx;
DROP INDEX IF EXISTS documents_collection_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_source_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_claim_group_idx;
CREATE INDEX documents_collection_scope_key_idx
ON documents (collection, json_extract(json, '$.scopeKey'))
WHERE json_valid(json);
CREATE INDEX documents_collection_memory_id_idx
ON documents (collection, json_extract(json, '$.memoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_source_memory_id_idx
ON documents (collection, json_extract(json, '$.sourceMemoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_claim_group_idx
ON documents (
collection,
json_extract(json, '$.scopeKey'),
json_extract(json, '$.subjectEntityId'),
json_extract(json, '$.predicateKey')
)
WHERE json_valid(json);
`),G.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(OG,_G);G.exec("COMMIT")}catch(Y){try{G.exec("ROLLBACK")}catch{}throw Y}}function lG(G){G.exec(`
CREATE TABLE IF NOT EXISTS session_buffers (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_working_memory (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_journals (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`)}function sG(G){G.exec(`
CREATE TABLE IF NOT EXISTS vectors (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding_json TEXT NOT NULL,
metadata_json TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE TABLE IF NOT EXISTS vector_index_state (
table_name TEXT PRIMARY KEY,
collection TEXT NOT NULL,
dimension INTEGER NOT NULL,
dirty INTEGER NOT NULL
);
`)}function V(G){return JSON.parse(G)}function g(G,Y){let Z=G.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(Y);return Z!==null&&Z!==void 0}function oG(G,Y,Z){let H=Y.replaceAll('"','""');return G.query(`PRAGMA table_info("${H}")`).all().some(({name:X})=>X===Z)}function f(G){return Error(`SQLite ${G} store is read-only in this context.`)}function iG(G,Y){let Z=Math.min(G.length,Y.length),H=0;for(let X=0;X<Z;X+=1)H+=G[X]*Y[X];return H}function nG(G){return G===null||typeof G==="string"||typeof G==="number"||typeof G==="boolean"}function aG(G){switch(G){case"memoryId":return"$.memoryId";case"predicateKey":return"$.predicateKey";case"scopeKey":return"$.scopeKey";case"sourceMemoryId":return"$.sourceMemoryId";case"subjectEntityId":return"$.subjectEntityId";default:return}}function n(G,Y){G.exec("BEGIN IMMEDIATE");try{let Z=Y();return G.exec("COMMIT"),Z}catch(Z){try{G.exec("ROLLBACK")}catch{}throw Z}}function KG(G){let{alias:Y,keyParameterIndex:Z,value:H,valueParameterIndex:X}=G,F=`EXISTS (
SELECT 1
FROM json_each(metadata_json) AS ${Y}
WHERE ${Y}.key = ?${Z}`;if(H===null)return`${F}
AND ${Y}.type = 'null'
)`;if(typeof H==="boolean")return`${F}
AND ${Y}.type = '${H?"true":"false"}'
)`;if(typeof H==="number")return`${F}
AND ${Y}.type IN ('integer', 'real')
AND ${Y}.atom = ?${X}
)`;return`${F}
AND ${Y}.type = 'text'
AND ${Y}.atom = ?${X}
)`}function c(G){return`"${G.replaceAll('"','""')}"`}function tG(G){if(/^[A-Za-z0-9]+$/.test(G))return G;return`x_${bG.from(G,"utf8").toString("hex")}`}function FG(G,Y){return`vss_vectors_${tG(G)}_dim_${Y}`}function i(G,Y,Z){G.query(`DELETE FROM ${c(Y)} WHERE rowid = ?1`).run(Z)}function MG(G){let{database:Y,embeddingJson:Z,rowid:H,tableName:X}=G;i(Y,X,H),Y.query(`INSERT INTO ${c(X)} (rowid, embedding)
VALUES (?1, json(?2))`).run(H,Z)}function eG(G){let{collection:Y,config:Z,database:H,filter:X,queryEmbedding:F,topK:W}=G;if(Z.mode==="off"||!Z.paths?.length)return null;let A=[Y,JSON.stringify(F)],M=[];if(X)for(let[U,Q]of Object.entries(X)){if(!nG(Q))return null;A.push(U);let N=A.length,I=`metadata_filter_${M.length+1}`;if(Q===null||typeof Q==="boolean"){M.push(KG({alias:I,keyParameterIndex:N,value:Q}));continue}A.push(Q),M.push(KG({alias:I,keyParameterIndex:N,value:Q,valueParameterIndex:A.length}))}A.push(W);let E=["collection = ?1",...M];return H.query(`SELECT
id,
embedding_json,
metadata_json,
content,
${Z.searchFunction||t}(embedding_json, ?2) AS score
FROM vectors
WHERE ${E.join(" AND ")}
ORDER BY score DESC, id ASC
LIMIT ?${A.length}`).all(...A).map((U)=>({id:U.id,embedding:V(U.embedding_json),metadata:V(U.metadata_json),content:U.content,score:Number(U.score)}))}function OY(G,Y){let Z=$G(G,Y);if(!Y?.readOnly)dG(Z);let H=Z.query(`INSERT INTO documents (collection, id, json)
VALUES (?1, ?2, ?3)
ON CONFLICT(collection, id) DO UPDATE SET json = excluded.json`),X=Z.query("SELECT json FROM documents WHERE collection = ?1 AND id = ?2"),F=Z.query("SELECT json FROM documents WHERE collection = ?1"),W=Z.query("DELETE FROM documents WHERE collection = ?1 AND id = ?2"),A=g(Z,"document_text_fts"),M=g(Z,"document_text_fts_keys"),E=A&&oG(Z,"document_text_fts","searchText"),P=M?Z.query(`INSERT OR IGNORE INTO document_text_fts_keys (collection, id)
VALUES (?1, ?2)`):null,U=M?Z.query(`SELECT rowid FROM document_text_fts_keys
WHERE collection = ?1 AND id = ?2`):null,Q=A?Z.query("DELETE FROM document_text_fts WHERE rowid = ?1"):null,N=A&&E?Z.query(`INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
VALUES (?1, ?2, ?3, ?4, ?5)`):null,I=M?Z.query("DELETE FROM document_text_fts_keys WHERE rowid = ?1"):null;function x(J,$){let O=U?.get(J,$);if(!O)return;Q?.run(O.rowid),I?.run(O.rowid)}function d(J,$,O){if(!Q||!N||!P||!U)return;let z=U.get(J,$);if(z)Q.run(z.rowid);let R=ZG(O,"searchText"),T=ZG(O,"text");if(T===void 0&&R===void 0){if(z)I?.run(z.rowid);return}P.run(J,$);let D=U.get(J,$);N.run(D.rowid,J,$,T??null,R??null)}function p(J){let $=Object.entries(J.filter??{}),O=$.length>0?[`json_valid(${J.alias}.json)`]:[];for(let[z,R]of $){let T=aG(z);if(T){if(R===null){O.push(`json_type(${J.alias}.json, '${T}') = 'null'`);continue}J.values.push(R),O.push(`json_extract(${J.alias}.json, '${T}') = ?${J.values.length}`);continue}J.values.push(`$."${z.replaceAll('"',"\\\"")}"`);let D=J.values.length;if(R===null){O.push(`json_type(${J.alias}.json, ?${D}) = 'null'`);continue}J.values.push(R),O.push(`json_extract(${J.alias}.json, ?${D}) = ?${J.values.length}`)}return O}function l(J){Z.exec("BEGIN IMMEDIATE");try{for(let $ of[J.expected,...J.unchanged??[]]){let O=X.get($.collection,$.id);if(!($.document===null?O===null:O!==null&&O.json===JSON.stringify($.document)))return Z.exec("ROLLBACK"),!1}for(let $ of J.set)H.run($.collection,$.id,JSON.stringify($.document)),d($.collection,$.id,$.document);for(let $ of J.delete??[])W.run($.collection,$.id),x($.collection,$.id);return Z.exec("COMMIT"),!0}catch($){try{Z.exec("ROLLBACK")}catch{}throw $}}return{projectionBatchSemantics:DG,async set(J,$,O){n(Z,()=>{H.run(J,$,JSON.stringify(O)),d(J,$,O)})},async get(J,$){let O=X.get(J,$);return O?V(O.json):null},async update(J,$,O){let z=await this.get(J,$);if(!z)throw Error(`Document not found for update: ${J}/${$}`);await this.set(J,$,EG(z,O))},async query(J,$){if(CG($),$&&Object.keys($).length>0){let z=[J],R=p({alias:"documents",filter:$,values:z});return Z.query(`SELECT json FROM documents
WHERE collection = ?1 AND ${R.join(" AND ")}`).all(...z).map((D)=>V(D.json))}return F.all(J).map((z)=>V(z.json))},async queryPage(J,$){qG($);let O=[J],z=p({alias:"documents",filter:$.filter,values:O});O.push($.cursor??null);let R=O.length;O.push($.limit+1);let T=Z.query(`SELECT documents.id, documents.json
FROM documents
WHERE documents.collection = ?1
${z.length>0?`AND ${z.join(" AND ")}`:""}
AND (?${R} IS NULL OR documents.id > ?${R})
ORDER BY documents.id ASC
LIMIT ?${O.length}`).all(...O),D=T.slice(0,$.limit);return{items:D.map((w)=>V(w.json)),...T.length>$.limit?{nextCursor:D.at(-1).id}:{}}},async searchText(J,$){kG($);let O=RG($.query);if(O.length===0)return[];let z=[],R,T=$.field==="text"?$.field:$.field==="searchText"&&E?$.field:null;if(A&&T){z.push(O,J);let D=p({alias:"documents",filter:$.filter,values:z});z.push($.limit),R=`SELECT documents.id, documents.json, bm25(document_text_fts) AS score
FROM document_text_fts
JOIN documents
ON documents.collection = document_text_fts.collection
AND documents.id = document_text_fts.id
WHERE document_text_fts.${T} MATCH ?1
AND document_text_fts.collection = ?2
${D.length>0?`AND ${D.join(" AND ")}`:""}
ORDER BY score ASC, documents.id ASC
LIMIT ?${z.length}`}else{z.push(J,`$."${$.field.replaceAll('"',"\\\"")}"`);let D=PG($.query),w=[];for(let v of D)z.push(`%${v}%`),w.push(`lower(CAST(json_extract(documents.json, ?2) AS TEXT)) LIKE ?${z.length}`);let u=p({alias:"documents",filter:$.filter,values:z});z.push($.limit),R=`SELECT documents.id, documents.json, 1 AS score
FROM documents
WHERE documents.collection = ?1
AND (${w.join(" OR ")})
${u.length>0?`AND ${u.join(" AND ")}`:""}
ORDER BY documents.id ASC
LIMIT ?${z.length}`}return Z.query(R).all(...z).map((D)=>({document:V(D.json),id:D.id,score:Math.max(Number.EPSILON,Math.abs(Number(D.score)))}))},async writeBatchIfUnchanged(J){if(Y?.readOnly)throw f("document");return l(J)},async delete(J,$){n(Z,()=>{x(J,$),W.run(J,$)})}}}function GG(G,Y,Z){if(Z?.readOnly&&!g(G,Y))return{async set(){throw f("session")},async get(){return null},async setIfUnchanged(){throw f("session")},async deleteIfUnchanged(){throw f("session")},async deleteByScope(){throw f("session")}};let H=G.query(`INSERT INTO ${Y} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO UPDATE SET json = excluded.json`),X=G.query(`SELECT json FROM ${Y} WHERE scope_key = ?1`),F=G.query(`INSERT INTO ${Y} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO NOTHING`),W=G.query(`UPDATE ${Y}
SET json = ?3
WHERE scope_key = ?1 AND json = ?2`),A=G.query(`DELETE FROM ${Y} WHERE scope_key = ?1`),M=G.query(`DELETE FROM ${Y} WHERE scope_key = ?1 AND json = ?2`),E=G.query(`DELETE FROM ${Y} WHERE scope_key LIKE ?1`);return{async set(P,U){H.run(b(P),JSON.stringify(U))},async setIfUnchanged(P,U,Q){return n(G,()=>{let N=b(P),I=JSON.stringify(Q),x=U===null?F.run(N,I):W.run(N,JSON.stringify(U),I);return Number(x.changes??0)===1})},async get(P){let U=X.get(b(P));return U?V(U.json):null},async deleteIfUnchanged(P,U){return n(G,()=>{let Q=M.run(b(P),JSON.stringify(U));return Number(Q.changes??0)===1})},async deleteByScope(P){if(P.sessionId!==void 0){let Q=A.run(b(P));return Number(Q.changes??0)}let U=E.run(`${QG(P)}%`);return Number(U.changes??0)}}}function UY(G,Y){let Z=$G(G,Y);if(!Y?.readOnly)lG(Z);let H=GG(Z,"session_buffers",Y),X=GG(Z,"session_working_memory",Y),F=GG(Z,"session_journals",Y);return{saveBuffer(W,A){return H.set(W,A)},saveBufferIfUnchanged(W,A,M){return H.setIfUnchanged(W,A,M)},getBuffer(W){return H.get(W)},deleteBufferIfUnchanged(W,A){return H.deleteIfUnchanged(W,A)},deleteBuffersByScope(W){return H.deleteByScope(W)},saveWorkingMemory(W,A){return X.set(W,A)},getWorkingMemory(W){return X.get(W)},deleteWorkingMemoryByScope(W){return X.deleteByScope(W)},saveJournal(W,A){return F.set(W,A)},getJournal(W){return F.get(W)},deleteJournalsByScope(W){return F.deleteByScope(W)}}}function zY(G,Y,Z){let H=Z?.runtimeResolution??TG(),X=Z?.vectorExtensionConfig??H.config.vectorExtension,F=Z?.runtimeResolution?.diagnostics??H.diagnostics,W=$G(G,Y);if(!Y?.readOnly)sG(W);if(F.requestedMode==="require"&&!F.available)throw Error(F.reason??"SQLite vector acceleration is required but no supported runtime is available.");let A=!Y?.readOnly||g(W,"vectors"),M=new Set,E=null,P=Y?.readOnly?null:W.query(`INSERT INTO vectors (
collection,
id,
embedding_json,
metadata_json,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(collection, id) DO UPDATE SET
embedding_json = excluded.embedding_json,
metadata_json = excluded.metadata_json,
content = excluded.content`),U=A?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,Q=A?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,N=A?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,I=A?W.query(`SELECT rowid, embedding_json
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,x=A?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND rowid = ?2`):null,d=Y?.readOnly?null:W.query("DELETE FROM vectors WHERE collection = ?1 AND id = ?2"),l=!Y?.readOnly||g(W,"vector_index_state")?W.query(`SELECT dirty
FROM vector_index_state
WHERE table_name = ?1`):null,J=Y?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 1)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 1`),$=Y?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 0)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 0`);function O(){if(E)return E;let j=(Z?.loadVectorExtension??AG)(X,W);return E=j&&typeof j==="object"&&"loaded"in j?j:{loaded:X.mode!=="off"&&Boolean(X.paths?.length)},E}function z(){return X.backend==="sqlite-vss"&&O().loaded}function R(j,K){let B=FG(j,K);J.run(B,j,K)}function T(j){$.run(j.tableName,j.collection,j.dimension)}function D(j){if(!j.existed)return!0;let K=l.get(j.tableName);return!K||K.dirty!==0}function w(j){return l?.get(j)?.dirty===0}function u(j,K,B){let _=N.all(j).filter((C)=>{return V(C.embedding_json).length===K}),q=new Set(_.map((C)=>C.rowid)),k=W.query(`SELECT rowid FROM ${c(B)}`).all();for(let C of k)if(!q.has(C.rowid))i(W,B,C.rowid);for(let C of _)MG({database:W,embeddingJson:C.embedding_json,rowid:C.rowid,tableName:B});T({collection:j,dimension:K,tableName:B})}function v(j,K){if(!z())return null;let B=FG(j,K);if(M.has(B)){if(Y?.readOnly){if(!w(B))return M.delete(B),null;return B}if(D({existed:!0,tableName:B}))u(j,K,B);return B}if(Y?.readOnly){if(!g(W,B))return null;if(!w(B))return null;return M.add(B),B}let _=g(W,B);if(W.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${c(B)}
USING vss0(embedding(${K}))`),D({existed:_,tableName:B}))u(j,K,B);return M.add(B),B}function IG(j){let{collection:K,filter:B,queryEmbedding:_,topK:q}=j,k=_.length,C=v(K,k);if(!C)return null;let L=Q.all(K).filter((h)=>{return V(h.embedding_json).length===k}).length;if(L===0)return[];let s=JSON.stringify(_),y=Math.min(L,Math.max(q,B?q*4:q));while(y>0){let h=W.query(`SELECT rowid, distance
FROM ${c(C)}
WHERE vss_search(embedding, vss_search_params(json(?1), ?2))`).all(s,y),S=[];for(let WG of h){let r=x.get(K,WG.rowid);if(!r)continue;let LG=V(r.embedding_json),XG=V(r.metadata_json);if(!YG(XG,B))continue;S.push({id:r.id,embedding:LG,metadata:XG,content:r.content,score:1/(1+Number(WG.distance))})}if(!B||S.length>=q||y>=L)return S.slice(0,q);y=Math.min(L,y*2)}return[]}return{async upsert(j,K){if(Y?.readOnly)throw f("vector");W.transaction((_)=>{let q=z();for(let k of _){let C=I.get(j,k.id),L=C?V(C.embedding_json).length:null,s=JSON.stringify(k.embedding);if(P.run(j,k.id,s,JSON.stringify(k.metadata),k.content),!q){if(C&&L!==null&&L!==k.embedding.length)R(j,L);R(j,k.embedding.length);continue}let y=I.get(j,k.id);if(!y)continue;if(C&&L!==null&&L!==k.embedding.length){let S=v(j,L);if(S)i(W,S,C.rowid)}let h=v(j,k.embedding.length);if(!h)continue;MG({database:W,embeddingJson:s,rowid:y.rowid,tableName:h})}})(K)},async get(j,K){if(!A)return null;let B=U.get(j,K);if(!B)return null;return{id:B.id,embedding:V(B.embedding_json),metadata:V(B.metadata_json),content:B.content}},async search(j,K,B){if(B.topK<=0||K.length===0)return[];if(!A)return[];if(X.mode!=="off"&&X.paths?.length&&O().loaded)try{let _=X.backend==="sqlite-vss"?IG({collection:j,filter:B.filter,queryEmbedding:K,topK:B.topK}):(Z?.runExtensionSearch??eG)({collection:j,config:X,database:W,filter:B.filter,queryEmbedding:K,topK:B.topK});if(_!==null)return _;if(X.mode==="require")throw Error("SQLite vector extension search could not satisfy the current query without durable fallback.")}catch(_){if(X.mode==="require"){let q=_ instanceof Error?_.message:String(_);throw Error(`Failed to execute SQLite vector extension search for ${j}: ${q}`)}}return Q.all(j).map((_)=>{let q=V(_.embedding_json),k=V(_.metadata_json);return{id:_.id,embedding:q,metadata:k,content:_.content,score:iG(q,K)}}).filter((_)=>YG(_.metadata,B.filter)).sort((_,q)=>{if(q.score!==_.score)return q.score-_.score;return _.id.localeCompare(q.id)}).slice(0,B.topK)},async delete(j,K){if(Y?.readOnly)throw f("vector");W.transaction(()=>{let _=I.get(j,K),q=z();if(_&&q){let k=V(_.embedding_json).length,C=v(j,k);if(C)i(W,C,_.rowid)}if(_&&!q){let k=V(_.embedding_json).length;R(j,k)}d.run(j,K)})()}}}export{zY as createSQLiteVectorStore,UY as createSQLiteSessionStore,OY as createSQLiteDocumentStore};
export{OY as Ra,UY as Sa,zY as Ta};

Sorry, the diff of this file is too big to display

import{createRequire as x}from"node:module";var f=Object.create;var{getPrototypeOf:S,defineProperty:g,getOwnPropertyNames:D}=Object;var y=Object.prototype.hasOwnProperty;var I=(e,t,o)=>{o=e!=null?f(S(e)):{};let r=t||!e||!e.__esModule?g(o,"default",{value:e,enumerable:!0}):o;for(let n of D(e))if(!y.call(r,n))g(r,n,{get:()=>e[n],enumerable:!0});return r};var b=x(import.meta.url);function c(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function d(e){let t=e.userId.trim();if(t.length===0)throw Error("MemoryScope requires a non-empty userId");return{userId:t,tenantId:c(e.tenantId),workspaceId:c(e.workspaceId),agentId:c(e.agentId),sessionId:c(e.sessionId)}}function l(e){let t=d(e);return[t.userId,t.tenantId??"",t.workspaceId??"",t.agentId??"",t.sessionId??""].join("::")}function M(e){let t=d(e);return[t.userId,t.tenantId??"",t.workspaceId??"",t.agentId??"",t.sessionId].map((o)=>o??"").join("::")}function B(e,t){return l(e)===l(t)}var v="unchanged-delete-v1";function k(e){return e.projectionBatchSemantics==="unchanged-delete-v1"&&typeof e.writeBatchIfUnchanged==="function"}function C(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document query page limit must be a positive integer.");p(e.filter)}function R(e){if(e.field.trim().length===0)throw Error("Document text search field must be non-empty.");if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document text search limit must be a positive integer.");p(e.filter)}function p(e){for(let t of Object.values(e??{}))if(t!==null&&typeof t!=="boolean"&&typeof t!=="string"&&(typeof t!=="number"||!Number.isFinite(t)))throw Error("Storage filters only support scalar equality values.")}function j(e,t){if(!t)return!0;let o=e;return Object.entries(t).every(([r,n])=>o[r]===n)}function E(e,t){return{...e,...t}}var h=/[\p{L}\p{N}]+/gu;function s(e){return(e.normalize("NFKC").toLowerCase().match(h)??[]).filter((t)=>t.length>0)}function F(e){return[...new Set(s(e))].map((t)=>`"${t.replaceAll('"','""')}"`).join(" OR ")}function N(e){let t=[...new Set(s(e))];return{substrings:t.map((o)=>`%${o}%`),tsQuery:t.join(" | ")}}function W(e,t){let o=e[t];return typeof o==="string"?o:void 0}function A(e,t){let o=[...new Set(s(e))];if(o.length===0)return 0;let r=s(t),n=new Map;for(let i of r)n.set(i,(n.get(i)??0)+1);let u=0,m=0;for(let i of o){let a=n.get(i)??0;if(a>0)u+=1,m+=a}if(u===0)return 0;return u/o.length+m/Math.max(1,r.length)}
export{I as Ua,b as Va,d as Wa,l as Xa,M as Ya,B as Za,v as _a,k as $a,C as ab,R as bb,p as cb,j as db,E as eb,s as fb,F as gb,N as hb,W as ib,A as jb};
import{_b as D}from"./chunk-n9j0rb5c.js";import{ac as q,cc as K}from"./chunk-eqpe4gcb.js";var S=q((kz,O)=>{var{create:m,defineProperty:v,getOwnPropertyDescriptor:_,getOwnPropertyNames:a,getPrototypeOf:n}=Object,r=Object.prototype.hasOwnProperty,t=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},I=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of a(B))if(!r.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=_(B,G))||H.enumerable})}return z},V=(z,B,F)=>(F=z!=null?m(n(z)):{},I(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),e=(z)=>I(v({},"__esModule",{value:!0}),z),M={};t(M,{findRootDir:()=>Bz,getUserDataDir:()=>Fz});O.exports=e(M);var Y=V(K("path")),o=V(K("fs")),J=V(K("os")),zz=D();function Bz(){try{let z=process.cwd();while(z!==Y.default.dirname(z)){let B=Y.default.join(z,".vercel");if(o.default.existsSync(B))return z;z=Y.default.dirname(z)}}catch(z){throw new zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Fz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(J.default.platform()){case"darwin":return Y.default.join(J.default.homedir(),"Library/Application Support");case"linux":return Y.default.join(J.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var u=q((fz,l)=>{var{create:Gz,defineProperty:b,getOwnPropertyDescriptor:Hz,getOwnPropertyNames:Kz,getPrototypeOf:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},j=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Kz(B))if(!Wz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=Hz(B,G))||H.enumerable})}return z},E=(z,B,F)=>(F=z!=null?Gz(Qz(z)):{},j(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Yz=(z)=>j(b({},"__esModule",{value:!0}),z),x={};Xz(x,{isValidAccessToken:()=>vz,readAuthConfig:()=>$z,writeAuthConfig:()=>qz});l.exports=Yz(x);var Z=E(K("fs")),y=E(K("path")),Zz=P();function C(){let z=(0,Zz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return y.join(z,"auth.json")}function $z(){try{let z=C();if(!Z.existsSync(z))return null;let B=Z.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function qz(z){let B=C(),F=y.dirname(B);if(!Z.existsSync(F))Z.mkdirSync(F,{mode:504,recursive:!0});Z.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function vz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var k=q((iz,g)=>{var{defineProperty:R,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz}=Object,Lz=Object.prototype.hasOwnProperty,Jz=(z,B)=>{for(var F in B)R(z,F,{get:B[F],enumerable:!0})},Vz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Lz.call(z,G)&&G!==F)R(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},Az=(z)=>Vz(R({},"__esModule",{value:!0}),z),c={};Jz(c,{processTokenResponse:()=>Dz,refreshTokenRequest:()=>Tz});g.exports=Az(c);var A=K("os"),Nz="https://vercel.com",Rz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",h=`@vercel/oidc node-${process.version} ${(0,A.platform)()} (${(0,A.arch)()}) ${(0,A.hostname)()}`,N=null;async function wz(){if(N)return N;let z=`${Nz}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":h}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return N=H,H}async function Tz(z){let B=await wz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":h},body:new URLSearchParams({client_id:Rz,grant_type:"refresh_token",...z})})}async function Dz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var P=q((dz,s)=>{var{create:Iz,defineProperty:U,getOwnPropertyDescriptor:Mz,getOwnPropertyNames:Oz,getPrototypeOf:Sz}=Object,jz=Object.prototype.hasOwnProperty,Ez=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},i=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Oz(B))if(!jz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=Mz(B,G))||H.enumerable})}return z},d=(z,B,F)=>(F=z!=null?Iz(Sz(z)):{},i(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),xz=(z)=>i(U({},"__esModule",{value:!0}),z),p={};Ez(p,{assertVercelOidcTokenResponse:()=>w,findProjectInfo:()=>uz,getTokenPayload:()=>hz,getVercelCliToken:()=>Cz,getVercelDataDir:()=>yz,getVercelOidcToken:()=>lz,isExpired:()=>gz,loadToken:()=>cz,saveToken:()=>Pz});s.exports=xz(p);var $=d(K("path")),Q=d(K("fs")),X=D(),L=S(),W=u(),f=k();function yz(){let B=(0,L.getUserDataDir)();if(!B)return null;return $.join(B,"com.vercel.cli")}async function Cz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,f.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,f.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function lz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return w(T),T}function w(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function uz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=$.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function Pz(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=$.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync($.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function cz(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=$.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return w(H),H}function hz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function gz(z){return z.exp*1000<Date.now()}});export default P();
export{P as Zb};
import{Jb as x,Lb as f,Mb as v,Qb as d,Sb as p}from"./chunk-g26g591p.js";import{Wb as M,Xb as g}from"./chunk-c28647f0.js";import"./chunk-eqpe4gcb.js";import{SQL as u}from"bun";var m="public",s="gm",C="gm_documents",S="gm_session_state",r="gm_storage_schema",N="document_indexes",V=1,o=/^[A-Za-z_][A-Za-z0-9_]*$/,i=[{method:"btree",methodAndKey:"USING btree (collection)",name:"gm_documents_collection_idx"},{method:"gin",methodAndKey:"USING gin (document)",name:"gm_documents_document_gin_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'text'), '')))",name:"gm_documents_text_search_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'searchText'), '')))",name:"gm_documents_search_text_search_idx"}],b=new Map;function l(G){let J=G.trim();if(J.length===0)throw Error("Postgres storage requires a non-empty url");return J}function T(G,J){if(!o.test(G))throw Error(`Invalid Postgres ${J}: ${G}. Use only letters, digits, and underscores, and start with a letter or underscore.`);return G}function j(G){return`"${G}"`}function B(G,J){return`${j(G)}.${j(J)}`}function c(G){return JSON.stringify(G)}function D(G){return c(G)}function z(G){if(typeof G!=="string")return G;let J=JSON.parse(G);if(typeof J!=="string")return J;try{return JSON.parse(J)}catch{return J}}function n(G){return Boolean(G&&Object.keys(G).length>0)}function A(G,J,F){if(!n(J))return"";return F.push(D(J)),` AND ${G} @> $${F.length}::text::jsonb`}function t(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`{${G.join(",")}}`}function e(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`[${G.join(",")}]`}function k(G){let J=null;return async()=>{if(!J)J=G().catch((F)=>{throw J=null,F});await J}}function I(G){return Error(`Postgres ${G} store is read-only in this context.`)}async function y(G,J){let F=await G.unsafe("SELECT to_regclass($1)::text AS oid",[J]);return F[0]?.oid!==null&&F[0]?.oid!==void 0}function R(G){let J=l(G.url),F=T(G.schema??m,"schema"),O=T(G.vectorTablePrefix??s,"vectorTablePrefix"),H=`${O}_vectors`,U=c({url:J,schema:F,vectorTablePrefix:O}),Q=b.get(U);if(Q)return Q;let W=new u(J,{prepare:!1}),X=j(F),_=B(F,C),$=B(F,S),Y=B(F,H),K=`${F}.${C}`,Z=`${F}.${S}`,E=`${F}.${H}`,P=k(async()=>{await W.unsafe(`CREATE SCHEMA IF NOT EXISTS ${X}`)}),L={sql:W,schema:F,documentTable:_,sessionStateTable:$,vectorTable:Y,hasDocumentStore:()=>y(W,K),hasSessionStore:()=>y(W,Z),hasVectorStore:()=>y(W,E),ensureDocumentStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${_} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
document JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`)}),ensureSessionStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${$} (
scope_key TEXT NOT NULL,
state_kind TEXT NOT NULL,
payload JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_key, state_kind)
)
`)}),ensureVectorStore:k(async()=>{await P(),await W.unsafe("CREATE EXTENSION IF NOT EXISTS vector"),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${Y} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding DOUBLE PRECISION[] NOT NULL,
metadata JSONB NOT NULL,
content TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_collection_idx`)}
ON ${Y} (collection)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_metadata_gin_idx`)}
ON ${Y} USING GIN (metadata)
`)})};return b.set(U,L),L}function q(G,J,F){return{async set(O,H){if(F?.readOnly)throw I("session");await G.ensureSessionStore(),await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind)
DO UPDATE SET
payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
`,[M(O),J,D(H)])},async setIfUnchanged(O,H,U){if(F?.readOnly)throw I("session");await G.ensureSessionStore();let Q=M(O);return(H===null?await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind) DO NOTHING
RETURNING 1 AS count
`,[Q,J,D(U)]):await G.sql.unsafe(`
UPDATE ${G.sessionStateTable}
SET
payload = $3::text::jsonb,
updated_at = NOW()
WHERE scope_key = $1
AND state_kind = $2
AND payload = $4::text::jsonb
RETURNING 1 AS count
`,[Q,J,D(U),D(H)])).length===1},async get(O){if(F?.readOnly&&!await G.hasSessionStore())return null;if(!F?.readOnly)await G.ensureSessionStore();let U=(await G.sql.unsafe(`
SELECT payload::text AS payload_json
FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
`,[M(O),J]))[0];return U?z(U.payload_json):null},async deleteIfUnchanged(O,H){if(F?.readOnly)throw I("session");return await G.ensureSessionStore(),(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1
AND state_kind = $2
AND payload = $3::text::jsonb
RETURNING 1 AS count
`,[M(O),J,D(H)])).length===1},async deleteByScope(O){if(F?.readOnly)throw I("session");if(await G.ensureSessionStore(),O.sessionId!==void 0)return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
RETURNING 1 AS count
`,[M(O),J])).length;return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key LIKE $1 AND state_kind = $2
RETURNING 1 AS count
`,[`${g(O)}%`,J])).length}}}function XF(G,J){let F=R(G);return{projectionBatchSemantics:x,async set(O,H,U){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[O,H,D(U)])},async get(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return null;if(!J?.readOnly)await F.ensureDocumentStore();let Q=(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H]))[0];return Q?z(Q.document_json):null},async update(O,H,U){if(J?.readOnly)throw I("document");if(await F.ensureDocumentStore(),(await F.sql.unsafe(`
UPDATE ${F.documentTable}
SET
document = document || $3::text::jsonb,
updated_at = NOW()
WHERE collection = $1 AND id = $2
RETURNING id
`,[O,H,D(U)])).length===0)throw Error(`Document not found for update: ${O}/${H}`)},async query(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H,U);return(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
ORDER BY id ASC
`,U)).map((X)=>z(X.document_json))},async queryPage(O,H){if(f(H),J?.readOnly&&!await F.hasDocumentStore())return{items:[]};if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H.filter,U);U.push(H.cursor??null);let W=U.length;U.push(H.limit+1);let X=U.length,_=await F.sql.unsafe(`
SELECT id, document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
AND ($${W}::text IS NULL OR id > $${W})
ORDER BY id ASC
LIMIT $${X}
`,U),$=_.slice(0,H.limit);return{items:$.map((Y)=>z(Y.document_json)),..._.length>H.limit?{nextCursor:$.at(-1).id}:{}}},async searchText(O,H){if(v(H),d(H.query).length===0)return[];if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=p(H.query),Q=H.field==="text"?"to_tsvector('simple', COALESCE(document ->> 'text', ''))":H.field==="searchText"?"to_tsvector('simple', COALESCE(document ->> 'searchText', ''))":null;if(Q){let Z=[O,U.tsQuery],E=A("document",H.filter,Z);return Z.push(H.limit),(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
ts_rank(
${Q},
to_tsquery('simple', $2)
) AS score
FROM ${F.documentTable}
WHERE collection = $1${E}
AND ${Q} @@ to_tsquery('simple', $2)
ORDER BY score DESC, id ASC
LIMIT $${Z.length}
`,Z)).map((L)=>({document:z(L.document_json),id:L.id,score:Number(L.score)}))}let W=[O,H.field,U.tsQuery],X=A("document",H.filter,W),$=U.substrings.map((Z)=>{return W.push(Z),W.length}).map((Z)=>`lower(COALESCE(document ->> $2, '')) LIKE $${Z}`).join(" OR ");W.push(H.limit);let Y=W.length;return(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
GREATEST(
ts_rank(
to_tsvector('simple', COALESCE(document ->> $2, '')),
to_tsquery('simple', $3)
),
CASE
WHEN ${$}
THEN 0.1
ELSE 0
END
) AS score
FROM ${F.documentTable}
WHERE collection = $1${X}
AND (
to_tsvector('simple', COALESCE(document ->> $2, ''))
@@ to_tsquery('simple', $3)
OR ${$}
)
ORDER BY score DESC, id ASC
LIMIT $${Y}
`,W)).map((Z)=>({document:z(Z.document_json),id:Z.id,score:Number(Z.score)}))},async writeBatchIfUnchanged(O){if(J?.readOnly)throw I("document");return await F.ensureDocumentStore(),F.sql.begin(async(H)=>{for(let U of[O.expected,...O.unchanged??[]]){await H.unsafe("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",[U.collection,U.id]);let Q=U.document===null?await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
FOR UPDATE
`,[U.collection,U.id]):await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
AND document = $3::text::jsonb
FOR UPDATE
`,[U.collection,U.id,D(U.document)]);if(!(U.document===null?Q.length===0:Q.length===1))return!1}for(let U of O.set)await H.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[U.collection,U.id,D(U.document)]);for(let U of O.delete??[])await H.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[U.collection,U.id]);return!0})},async delete(O,H){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}function YF(G,J){let F=R(G),O=q(F,"buffer",J),H=q(F,"working_memory",J),U=q(F,"journal",J);return{saveBuffer(Q,W){return O.set(Q,W)},saveBufferIfUnchanged(Q,W,X){return O.setIfUnchanged(Q,W,X)},getBuffer(Q){return O.get(Q)},deleteBufferIfUnchanged(Q,W){return O.deleteIfUnchanged(Q,W)},deleteBuffersByScope(Q){return O.deleteByScope(Q)},saveWorkingMemory(Q,W){return H.set(Q,W)},getWorkingMemory(Q){return H.get(Q)},deleteWorkingMemoryByScope(Q){return H.deleteByScope(Q)},saveJournal(Q,W){return U.set(Q,W)},getJournal(Q){return U.get(Q)},deleteJournalsByScope(Q){return U.deleteByScope(Q)}}}function ZF(G,J){let F=R(G);return{async upsert(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.begin(async(U)=>{for(let Q of H)await U.unsafe(`
INSERT INTO ${F.vectorTable} (
collection,
id,
embedding,
metadata,
content,
updated_at
) VALUES (
$1,
$2,
$3::double precision[],
$4::text::jsonb,
$5,
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
embedding = EXCLUDED.embedding,
metadata = EXCLUDED.metadata,
content = EXCLUDED.content,
updated_at = EXCLUDED.updated_at
`,[O,Q.id,t(Q.embedding),D(Q.metadata),Q.content])})},async get(O,H){if(J?.readOnly&&!await F.hasVectorStore())return null;if(!J?.readOnly)await F.ensureVectorStore();let Q=(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
0 AS score
FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
LIMIT 1
`,[O,H]))[0];if(!Q)return null;return{id:Q.id,embedding:z(Q.embedding_json),metadata:z(Q.metadata_json),content:Q.content}},async search(O,H,U){if(U.topK<=0||H.length===0)return[];if(J?.readOnly&&!await F.hasVectorStore())return[];if(!J?.readOnly)await F.ensureVectorStore();let Q=[O],W=A("metadata",U.filter,Q);Q.push(e(H));let X=Q.length;Q.push(U.topK);let _=Q.length;return(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
((embedding::vector <#> $${X}::vector) * -1) AS score
FROM ${F.vectorTable}
WHERE collection = $1${W}
ORDER BY embedding::vector <#> $${X}::vector ASC, id ASC
LIMIT $${_}
`,Q)).map((Y)=>({id:Y.id,embedding:z(Y.embedding_json),metadata:z(Y.metadata_json),content:Y.content,score:Number(Y.score)}))},async delete(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.unsafe(`
DELETE FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}async function a(G){let F=await R(G).sql.unsafe(`
SELECT
EXISTS (
SELECT 1
FROM pg_extension
WHERE extname = 'vector'
) AS installed,
EXISTS (
SELECT 1
FROM pg_available_extensions
WHERE name = 'vector'
) AS available
`);if(F[0]?.installed)return"installed";if(F[0]?.available)return"available";return"missing"}function FF(G){let J=B(G.schema,r);return{async runExclusive(F){let O=await G.sql.reserve(),H=["goodmemory",G.schema,N].join(":");try{return await O.unsafe("SELECT pg_advisory_lock(hashtextextended($1, 0))",[H]),await F()}finally{try{await O.unsafe("SELECT pg_advisory_unlock(hashtextextended($1, 0))",[H])}finally{O.release()}}},async createDocumentIndex(F){await G.sql.unsafe(F)},ensureDocumentStore:G.ensureDocumentStore,async ensureVersionStore(){await G.sql.unsafe(`
CREATE TABLE IF NOT EXISTS ${J} (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`)},async getDocumentIndex(F){let H=(await G.sql.unsafe(`
SELECT
pg_get_indexdef(index_relation.oid) AS definition,
index_metadata.indpred IS NOT NULL AS is_partial,
index_metadata.indisready AS is_ready,
index_metadata.indisunique AS is_unique,
index_metadata.indisvalid AS is_valid,
access_method.amname AS method,
table_relation.relname AS table_name,
table_namespace.nspname AS table_schema
FROM pg_class AS index_relation
JOIN pg_namespace AS index_namespace
ON index_namespace.oid = index_relation.relnamespace
JOIN pg_index AS index_metadata
ON index_metadata.indexrelid = index_relation.oid
JOIN pg_class AS table_relation
ON table_relation.oid = index_metadata.indrelid
JOIN pg_namespace AS table_namespace
ON table_namespace.oid = table_relation.relnamespace
JOIN pg_am AS access_method
ON access_method.oid = index_relation.relam
WHERE index_namespace.nspname = $1
AND index_relation.relname = $2
`,[G.schema,F]))[0];return H?{definition:H.definition,isPartial:H.is_partial,isReady:H.is_ready,isUnique:H.is_unique,isValid:H.is_valid,method:H.method,tableName:H.table_name,tableSchema:H.table_schema}:null},async getVersion(){return(await G.sql.unsafe(`
SELECT version
FROM ${J}
WHERE component = $1
`,[N]))[0]?.version??null},async setVersion(F){await G.sql.unsafe(`
INSERT INTO ${J} AS storage_schema (
component,
version,
updated_at
)
VALUES ($1, $2, NOW())
ON CONFLICT (component)
DO UPDATE SET
version = GREATEST(storage_schema.version, EXCLUDED.version),
updated_at = EXCLUDED.updated_at
`,[N,F])}}}function w(G){let J=G.toLocaleLowerCase("en-US"),F=J.startsWith("using ")?0:J.indexOf(" using ");if(F<0)return"";let O=G.slice(F),H=!1,U="";for(let Q=0;Q<O.length;Q+=1){let W=O[Q];if(W==="'"){if(U+=W,H&&O[Q+1]==="'")U+="'",Q+=1;else H=!H;continue}if(H){U+=W;continue}let X=O.slice(Q).toLocaleLowerCase("en-US"),_=["::regconfig","::text"].find(($)=>X.startsWith($));if(_){Q+=_.length-1;continue}if(W==='"'||/\s/.test(W))continue;U+=W.toLocaleLowerCase("en-US")}return U}function h(G,J,F){if(!(F!==null&&F.isValid&&F.isReady&&!F.isUnique&&!F.isPartial&&F.method.toLocaleLowerCase("en-US")===J.method&&F.tableName===C&&F.tableSchema===G&&w(F.definition)===w(J.methodAndKey)))throw Error(`Postgres document index ${G}.${J.name} exists but is invalid or has an unexpected definition. Drop it with DROP INDEX CONCURRENTLY and rerun the migration.`)}function GF(G){console.error(`[GoodMemory Postgres migration] status=${G.status} schema=${G.schema} index=${G.index} elapsedMs=${G.elapsedMs}`)}async function _F(G,J,F){l(G.url);let O=T(G.schema??m,"schema"),H=F?.port??FF(R(G)),U=J?.log??GF;await H.runExclusive(async()=>{await H.ensureDocumentStore(),await H.ensureVersionStore();let Q=await H.getVersion();if(Q!==null&&Q>V)throw Error(`Postgres document index schema ${O} has unsupported version ${Q}.`);for(let W of i){let X=await H.getDocumentIndex(W.name);if(X){h(O,W,X),U({elapsedMs:0,index:W.name,schema:O,status:"current"});continue}let _=Date.now();U({elapsedMs:0,index:W.name,schema:O,status:"creating"}),await H.createDocumentIndex(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${j(W.name)} ON ${B(O,C)} ${W.methodAndKey}`);let $=await H.getDocumentIndex(W.name);h(O,W,$),U({elapsedMs:Date.now()-_,index:W.name,schema:O,status:"created"})}if(Q!==V)await H.setVersion(V)})}async function HF(G){let J=R(G);await J.ensureDocumentStore(),await J.ensureSessionStore(),await J.ensureVectorStore()}async function JF(G){let J=R(G),[F,O,H]=await Promise.all([J.hasDocumentStore(),J.hasSessionStore(),J.hasVectorStore()]);return F&&O&&H}async function $F(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.hasExistingStorageBackend??JF,H=await F(G);if(H==="missing")return"unusable";if(H!=="installed")return"inconclusive";return await O(G)?"readable":"inconclusive"}async function DF(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.ensureStorageBackend??HF;if(await F(G)==="missing")return!1;return await O(G),!0}export{$F as probeReadOnlyPostgresStorageBackend,_F as migratePostgresStorageBackend,a as getPostgresVectorExtensionStatus,HF as ensurePostgresStorageBackend,ZF as createPostgresVectorStore,YF as createPostgresSessionStore,XF as createPostgresDocumentStore,DF as canBootstrapPostgresStorageBackend};
import{Ib as Id}from"./chunk-jr0h5wkn.js";function Kd(d){return d.lifecycle??"active"}function YI(d){return Kd(d)==="active"}function ZI(d,I){let M=new Date(I).getTime();if(Number.isNaN(M))return!1;for(let E of[d.validUntil,d.expiresAt]){if(E===void 0)continue;let R=new Date(E).getTime();if(!Number.isNaN(R)&&R<=M)return!0}return!1}function W(d){let I=d?.trim().toLowerCase();return I&&I.length>0?I:"general_response"}function JI(d){return[d.kind,W(d.appliesTo),d.normalizedRule.trim().toLowerCase()].join("\x00")}function h(d){return d?.extractedAt??new Date(0).toISOString()}function VI(d){let I=d.updatedAt??d.createdAt??new Date(0).toISOString();return{userId:d.userId,identity:d.identity??{},expertise:d.expertise??{primarySkills:[],domains:[]},activeContext:d.activeContext??{goals:[],currentProjects:[]},version:d.version??1,updatedAt:d.updatedAt??I,createdAt:d.createdAt??I}}function TI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,category:d.category,value:d.value,tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,source:d.source,evidenceCount:d.evidenceCount??1,isPinned:d.isPinned,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",updatedAt:d.updatedAt??h(d.source)}}function mI(d){let I=d.createdAt??d.updatedAt??h(d.source);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,category:d.category,content:d.content,tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,importance:d.importance??1,source:d.source,factKind:d.factKind,scopeKind:d.scopeKind,subject:d.subject,accessCount:d.accessCount??0,lastAccessedAt:d.lastAccessedAt,verificationPressureCount:d.verificationPressureCount??0,lastVerificationHintAt:d.lastVerificationHintAt,observedAt:d.observedAt,validFrom:d.validFrom,validUntil:d.validUntil,expiresAt:d.expiresAt,demotedAt:d.demotedAt,demotionReason:d.demotionReason,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",isActive:d.isActive??!0,embeddingId:d.embeddingId,createdAt:d.createdAt??I,updatedAt:d.updatedAt??I}}function QI(d){let I=d.createdAt??d.updatedAt??h(d.source);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,title:d.title,pointer:d.pointer,description:d.description,confidence:d.confidence??1,source:d.source,referenceKind:d.referenceKind,subject:d.subject,tags:d.tags,attributes:d.attributes,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",createdAt:d.createdAt??I,updatedAt:d.updatedAt??I}}function WI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,summary:d.summary,keyDecisions:d.keyDecisions??[],unresolvedItems:d.unresolvedItems??[],topics:d.topics??[],entities:d.entities,emotionalTone:d.emotionalTone,importance:d.importance??1,confidence:d.confidence??1,locale:d.locale,embeddingId:d.embeddingId,createdAt:d.createdAt??new Date(0).toISOString(),archivedAt:d.archivedAt}}function zI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,rule:d.rule,kind:d.kind,appliesTo:d.appliesTo,why:d.why,evidence:d.evidence??[],tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,source:d.source,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",lastUsedAt:d.lastUsedAt,updatedAt:d.updatedAt??h(d.source)}}function BI(d){let I=d.createdAt??d.lastActiveAt??new Date(0).toISOString();return{sessionId:d.sessionId,userId:d.userId,messages:d.messages??[],compactedMessages:d.compactedMessages??[],summary:d.summary??null,summaryUpToIndex:d.summaryUpToIndex??0,createdAt:d.createdAt??I,lastActiveAt:d.lastActiveAt??I}}function bI(d){return{sessionId:d.sessionId,userId:d.userId,currentGoal:d.currentGoal,constraints:d.constraints,openLoops:d.openLoops??[],temporaryDecisions:d.temporaryDecisions,toolState:d.toolState,state:d.state,updatedAt:d.updatedAt??new Date(0).toISOString()}}function FI(d){return{sessionId:d.sessionId,userId:d.userId,title:d.title,currentState:d.currentState,taskSpecification:d.taskSpecification,filesAndFunctions:d.filesAndFunctions??[],workflow:d.workflow??[],errorsAndCorrections:d.errorsAndCorrections??[],systemDocumentation:d.systemDocumentation??[],learnings:d.learnings??[],keyResults:d.keyResults??[],worklog:d.worklog??[],lastSummarizedMessageId:d.lastSummarizedMessageId,updatedAt:d.updatedAt??new Date(0).toISOString()}}function hI(d){return{...d}}var $d={active:["active","superseded","inactive"],superseded:["superseded","inactive"],inactive:["inactive","active"]};function vI(d,I){if(!$d[d].includes(I))throw Error(`Invalid lifecycle transition: ${d} -> ${I}`);return I}var Xd=Symbol.for("goodmemory.authorizedRecallAgentScope");function oI(d,I){return{...d,memoryType:I}}function wI(d,I){if(d.tenantId===void 0&&I.tenantId!==void 0)return!1;if(d.workspaceId===void 0&&I.workspaceId!==void 0)return!1;if(d.agentId===void 0&&I.agentId!==void 0)return!1;return!0}function qI(d,I){if(I.agentId===d.agentId)return!0;return d.agentId!==void 0&&I[Xd]===d.agentId}function f(d){if(d.enactmentSurface!=="text_response")return!1;return Boolean(d.applicability.textResponsePlan||d.applicability.computedResponseRule||d.applicability.urlTemplate||d.applicability.pathTemplate||d.applicability.guard||d.applicability.guardedBehavior||(d.applicability.replacementPairs?.length??0)>0||(d.applicability.forbiddenFragments?.length??0)>0||(d.applicability.preferredAlternatives?.length??0)>0||(d.applicability.preferredFragments?.length??0)>0||(d.applicability.exactFragments?.prefixes?.length??0)>0||(d.applicability.exactFragments?.required?.length??0)>0||(d.applicability.exactFragments?.suffixes?.length??0)>0)}function Yd(d){if(d.enactmentSurface!=="host_action")return!1;return Boolean(d.applicability.canonicalFirstAction||(d.applicability.argumentOrder?.length??0)>0)}var Ed="goodmemory.behavioral_policy",Md="goodmemory.behavioral_policy.steering_only",Zd="goodmemory.behavioral_policy.version",Jd=2,w=Id(),u={from:"http://",to:"https://"},Vd="<page>",t=/\.[A-Za-z0-9]{2,8}/u,Rd={first_action:8,syntax_constraint:7,guarded_policy:6,format_contract:5,avoidance:4,preference:3,transformation_rule:2,exemplar_fact:1},Sd={example_only:3,pattern_bounded:2,general:1};function T(d){return d?.trim().toLowerCase()??""}function B(d){if(!d?.trim())return;let I=w.resolveFromText({text:d});return w.analyzeBehavioralRule(d,I)}function X(d){let I=[],M=new Set;for(let E of d){let R=E?.trim();if(!R||M.has(R))continue;M.add(R),I.push(R)}return I}function Pd(d){return{...d,args:d.args&&d.args.length>0?[...d.args]:void 0,raw:d.raw?.trim()||void 0}}function kd(d){return[...d.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/gu)].map((I)=>I[1]??I[2]??I[3]??"").filter((I)=>I.length>0)}function Td(d){let I=[],M="",E=0,R=null;for(let P=0;P<d.length;P+=1){let k=d[P];if(R){if(M+=k,k===R&&d[P-1]!=="\\")R=null;continue}if(k==="'"||k==='"'){R=k,M+=k;continue}if(k==="("||k==="["||k==="{"){E+=1,M+=k;continue}if(k===")"||k==="]"||k==="}"){E=Math.max(0,E-1),M+=k;continue}if(k===","&&E===0){let O=M.trim();if(O.length>0)I.push(O);M="";continue}M+=k}let S=M.trim();if(S.length>0)I.push(S);return I}function r(d){let I=d.split(/\r?\n/u).map((R)=>R.trim()).find((R)=>R.length>0)??d.trim();if(!I)return;let M=I.match(/^([A-Za-z_][A-Za-z0-9_]*)\((.*)\)$/u);if(M){let[,R,S]=M;return{args:Td(S),kind:"tool_call",name:R,raw:I}}let E=kd(I);if(E.length===0)return;return{args:E.slice(1),kind:"command",name:E[0],raw:I}}function i(d){let I=Pd(d);if(I.args&&I.args.length>0)return I.args;if(I.kind==="warning"||!I.raw||I.raw.trim().length===0)return;let M=kd(I.raw);return M.length>1?M.slice(1):void 0}function md(d,I){if(I.length===0)return!0;let M=0;for(let E of I){let R=!1;while(M<d.length){if(d[M]===E){R=!0,M+=1;break}M+=1}if(!R)return!1}return!0}function p(d){let I=Pd(d);return JSON.stringify({...I.args?{args:I.args}:{},kind:I.kind,name:I.name,...I.raw?{raw:I.raw}:{}})}function Qd(d,I){if(!d||!I)return d===I;return p(d)===p(I)}function aI(d,I){if(!d||!I)return d===I;if(d.kind!==I.kind||d.name.trim()!==I.name.trim())return!1;if(I.kind==="warning")return Qd(d,I);let M=i(I);if(!M||M.length===0)return!0;let E=i(d);if(!E||E.length===0)return!1;return md(E,M)}function Wd(d){if(!A(d))return;if(d.kind!=="command"&&d.kind!=="tool_call"&&d.kind!=="warning"||typeof d.name!=="string")return;let I=Array.isArray(d.args)&&d.args.every((M)=>typeof M==="string")?[...d.args]:void 0;return{...I?{args:I}:{},kind:d.kind,name:d.name,...typeof d.raw==="string"?{raw:d.raw}:{}}}function Od(d){if(!A(d))return;let I=g(d.prefixes),M=g(d.required),E=g(d.suffixes);if(!I&&!M&&!E)return;return{...I?{prefixes:I}:{},...M?{required:M}:{},...E?{suffixes:E}:{}}}function l(d){if(!A(d)||typeof d.from!=="string"||typeof d.to!=="string")return;let I=d.from.trim(),M=d.to.trim();if(I.length===0||M.length===0)return;return{from:I,to:M}}function zd(d){if(!A(d)||typeof d.check!=="string")return;let I=d.check.trim();if(I.length===0)return;let M=g(d.allowedStates),E=typeof d.fallbackInstruction==="string"&&d.fallbackInstruction.trim().length>0?d.fallbackInstruction.trim():void 0,R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...M?{allowedStates:M}:{},check:I,...E?{fallbackInstruction:E}:{},...R?{subject:R}:{}}}function xd(d){if(!A(d)||typeof d.warningMessage!=="string")return;let I=d.warningMessage.trim();if(I.length===0)return;let M=g(d.preferredAlternatives),E=typeof d.replacementTarget==="string"&&d.replacementTarget.trim().length>0?d.replacementTarget.trim():void 0,R=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...R?{backupMention:R}:{},...M?{preferredAlternatives:M}:{},...E?{replacementTarget:E}:{},warningMessage:I}}function Bd(d){if(!A(d)||typeof d.precondition!=="string")return;let I=d.precondition.trim(),M=xd(d.fallbackBehavior);if(I.length===0||!M)return;let E=g(d.allowedWhen),R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...E?{allowedWhen:E}:{},fallbackBehavior:M,precondition:I,...R?{subject:R}:{}}}function e(d){if(!A(d)||typeof d.example!=="string"||typeof d.host!=="string"||d.pathPlacement!=="path_after_host"||d.scheme!=="http"&&d.scheme!=="https")return;let I=d.example.trim(),M=d.host.trim();if(I.length===0||M.length===0)return;return{example:I,host:M,pathPlacement:"path_after_host",scheme:d.scheme}}function a(d){if(!A(d)||typeof d.anchor!=="string"||typeof d.example!=="string"||d.variableSegment!=="filename")return;let I=d.anchor.trim(),M=d.example.trim();if(I.length===0||M.length===0)return;return{anchor:I,example:M,variableSegment:"filename"}}function _d(d){if(!A(d)||typeof d.kind!=="string")return;if(d.kind==="recurrence"){if(typeof d.sequenceName!=="string"||typeof d.expression!=="string")return;let I=d.sequenceName.trim(),M=d.expression.trim(),E=Array.isArray(d.baseCases)?d.baseCases.map((R)=>{if(!A(R)||typeof R.index!=="number"||typeof R.value!=="number"||!Number.isInteger(R.index)||!Number.isFinite(R.value))return;return{index:R.index,value:R.value}}).filter((R)=>Boolean(R)):void 0;if(I.length===0||M.length===0)return;return{...E&&E.length>0?{baseCases:E}:{},expression:M,kind:"recurrence",sequenceName:I}}if(d.kind==="binary_operator"){if(typeof d.expression!=="string"||typeof d.leftVariable!=="string"||typeof d.operatorSymbol!=="string"||typeof d.rightVariable!=="string")return;let I=d.expression.trim(),M=d.leftVariable.trim(),E=d.operatorSymbol.trim(),R=d.rightVariable.trim();if(I.length===0||M.length===0||E.length===0||R.length===0)return;return{expression:I,kind:"binary_operator",leftVariable:M,operatorSymbol:E,rightVariable:R}}return}function bd(d){if(!A(d)||d.kind!=="rewrite_output_slot")return;let I=Od(d.exactFragments),M=a(d.pathTemplate),E=g(d.preferredAlternatives),R=g(d.preferredFragments),S=Array.isArray(d.replacementPairs)?d.replacementPairs.map((O)=>l(O)).filter((O)=>Boolean(O)):void 0,P=e(d.urlTemplate),k=_d(d.computedResponseRule);if(!k&&!I&&!M&&!E&&!R&&!S&&!P)return;return{...k?{computedResponseRule:k}:{},...I?{exactFragments:I}:{},kind:"rewrite_output_slot",...M?{pathTemplate:M}:{},...E?{preferredAlternatives:E}:{},...R?{preferredFragments:R}:{},...S&&S.length>0?{replacementPairs:S}:{},...P?{urlTemplate:P}:{}}}function Fd(d){if(!A(d)||d.kind!=="require_warning"||typeof d.warningMessage!=="string")return;let I=d.warningMessage.trim();if(I.length===0)return;let M=g(d.preferredAlternatives),E=a(d.pathTemplate),R=typeof d.replacementTarget==="string"&&d.replacementTarget.trim().length>0?d.replacementTarget.trim():void 0,S=e(d.urlTemplate),P=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...P?{backupMention:P}:{},kind:"require_warning",...E?{pathTemplate:E}:{},...M?{preferredAlternatives:M}:{},...R?{replacementTarget:R}:{},...S?{urlTemplate:S}:{},warningMessage:I}}function fd(d){if(!A(d)||d.kind!=="block_surface")return;let I=g(d.forbiddenFragments);if(!I)return;let M=Array.isArray(d.replacementPairs)?d.replacementPairs.map((R)=>l(R)).filter((R)=>Boolean(R)):void 0,E=typeof d.fallbackAnswer==="string"&&d.fallbackAnswer.trim().length>0?d.fallbackAnswer.trim():void 0;return{...E?{fallbackAnswer:E}:{},forbiddenFragments:I,kind:"block_surface",...M&&M.length>0?{replacementPairs:M}:{}}}function hd(d){if(!A(d)||d.kind!=="require_precondition_check"||typeof d.precondition!=="string")return;let I=d.precondition.trim(),M=xd(d.fallbackBehavior);if(I.length===0||!M)return;let E=g(d.allowedWhen),R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...E?{allowedWhen:E}:{},fallbackBehavior:M,kind:"require_precondition_check",precondition:I,...R?{subject:R}:{}}}function vd(d){return bd(d)??Fd(d)??fd(d)??hd(d)}function yd(d){if(!A(d)||!Array.isArray(d.operations))return;let I=d.operations.map((M)=>vd(M)).filter((M)=>Boolean(M));if(I.length===0)return;return{...d.bulletOnly===!0?{bulletOnly:!0}:{},...d.brevityOnly===!0?{brevityOnly:!0}:{},concise:d.concise!==!1,operations:I}}function od(d){if(!A(d))return;let I=g(d.actionSummaryContains),M=g(d.queryContains),E=g(d.argumentOrder),R=Od(d.exactFragments),S=g(d.forbiddenFragments),P=g(d.preferredAlternatives),k=g(d.preferredFragments),O=a(d.pathTemplate),s=_d(d.computedResponseRule),G=Array.isArray(d.replacementPairs)?d.replacementPairs.map((U)=>l(U)).filter((U)=>Boolean(U)):void 0,Q=e(d.urlTemplate),j=zd(d.guard),H=Bd(d.guardedBehavior)??(j?{allowedWhen:j.allowedStates,fallbackBehavior:{warningMessage:j.fallbackInstruction??"Warn or defer instead of assuming the precondition already passed."},precondition:j.check,...j.subject?{subject:j.subject}:{}}:void 0),C=Wd(d.canonicalFirstAction),x=yd(d.textResponsePlan),D=typeof d.appliesTo==="string"?W(d.appliesTo):void 0,c=typeof d.fallbackInstruction==="string"&&d.fallbackInstruction.trim().length>0?d.fallbackInstruction.trim():void 0,K=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...I?{actionSummaryContains:I}:{},...D?{appliesTo:D}:{},...E?{argumentOrder:E}:{},...K?{backupMention:K}:{},...C?{canonicalFirstAction:C}:{},...s?{computedResponseRule:s}:{},...R?{exactFragments:R}:{},...c?{fallbackInstruction:c}:{},...S?{forbiddenFragments:S}:{},...j?{guard:j}:{},...H?{guardedBehavior:H}:{},...P?{preferredAlternatives:P}:{},...k?{preferredFragments:k}:{},...O?{pathTemplate:O}:{},...M?{queryContains:M}:{},...G&&G.length>0?{replacementPairs:G}:{},...x?{textResponsePlan:x}:{},...Q?{urlTemplate:Q}:{}}}function A(d){return typeof d==="object"&&d!==null}function g(d){if(!Array.isArray(d)||!d.every((M)=>typeof M==="string"))return;let I=X(d);return I.length>0?I:void 0}function wd(d){if(!A(d))return;if(d.behavioralKind!=="preference"&&d.behavioralKind!=="avoidance"&&d.behavioralKind!=="guarded_policy"&&d.behavioralKind!=="format_contract"&&d.behavioralKind!=="first_action"&&d.behavioralKind!=="syntax_constraint"&&d.behavioralKind!=="transformation_rule"&&d.behavioralKind!=="exemplar_fact")return;if(d.transferMode!=="example_only"&&d.transferMode!=="pattern_bounded"&&d.transferMode!=="general")return;if(d.enactmentSurface!=="text_response"&&d.enactmentSurface!=="host_action")return;return{behavioralKind:d.behavioralKind,enactmentSurface:d.enactmentSurface,applicability:od(d.applicability)??{},transferMode:d.transferMode}}function qd(d){return JSON.stringify(d)}function rd(d){if(d.enactmentSurface==="host_action")return!1;let I=d.applicability;return Boolean(I.argumentOrder||I.canonicalFirstAction||I.exactFragments||I.fallbackInstruction||I.forbiddenFragments&&I.forbiddenFragments.length>0||I.guard||I.guardedBehavior||I.pathTemplate||I.preferredAlternatives&&I.preferredAlternatives.length>0||I.replacementPairs&&I.replacementPairs.length>0||I.textResponsePlan||I.urlTemplate)}function uI(d,I){return{...d??{},[Ed]:qd(I),...rd(I)?{[Md]:!0}:{},[Zd]:Jd}}function ld(d){let I=d?.[Ed];if(typeof I!=="string"||I.trim().length===0)return;try{return wd(JSON.parse(I))}catch{return}}function sd(d){return ld(d.attributes)}function tI(d){return d.attributes?.[Md]===!0}function ed(d){if(d.exemplarCount!==void 0&&d.exemplarCount<=1&&!d.hasGeneralRuleMarker)return"example_only";if(d.hasGeneralRuleMarker)return"general";return(d.exemplarCount??0)>=2?"pattern_bounded":"example_only"}function ad(d){let{forbidden:I,preferred:M}=d,E=I.match(t)?.[0],R=M.match(t)?.[0],S=[];if(!I.startsWith(".")||M.startsWith("."))S.push({from:I,to:M});if(E&&R)S.push({from:E,to:R});return{forbiddenFragments:X([I,E]),preferredFragments:X([M,R]),replacementPairs:Cd(S)}}function ud(d){let{target:I,preferredAlternative:M}=d;return{fallbackInstruction:`Warn and route to ${M??"a specialist path"} instead of using the distrusted default path.`,forbiddenFragments:[I],...M?{preferredAlternatives:[M]}:{},queryContains:[I]}}function td(d){let{allowedStates:I,check:M,subject:E}=d;return{...I.length>0?{allowedStates:I}:{},check:M,fallbackInstruction:`Check ${M} first${I.length>0?` and only proceed when ${I.join(" or ")}`:""}; otherwise warn or defer instead of assuming it already passed.`,...E?{subject:E}:{}}}function id(d){let I,M;if(d.template){let E=d.template,R=new URL(E.replace(Vd,"page"));I=[`${R.protocol}//${R.host}/`],M={example:E,host:R.host,pathPlacement:"path_after_host",scheme:R.protocol==="https:"?"https":"http"}}return{fallbackInstruction:"If the current probe explicitly requests http, warn first and then offer the https URL instead of silently substituting protocols.",forbiddenFragments:[u.from],...I?{preferredFragments:I}:{},queryContains:["url"],replacementPairs:[u],...M?{urlTemplate:M}:{}}}function pd(d){let{forbiddenRoot:I,safeTemplate:M}=d,E,R;if(M){let S=M,P=S.replace(/<file>$/u,"");E=[P],R={anchor:P,example:S,variableSegment:"filename"}}if(!I&&!R&&!d.userHomeRequired)return null;return{fallbackInstruction:"Refuse the unsafe path and redirect to a safe user-writable home-directory path instead.",...I?{forbiddenFragments:[I]}:{},...E?{preferredFragments:E}:d.userHomeRequired?{preferredFragments:["/home/"]}:{},...R?{pathTemplate:R}:{}}}function nd(d){return d?.[0]}function dI(d){let I=d.fallbackInstruction??(d.preferredAlternatives&&d.preferredAlternatives.length>0?`Warn first and redirect to ${d.preferredAlternatives.join(" or ")} instead of proceeding directly.`:void 0);if(!I)return;return{...d.backupMention?{backupMention:d.backupMention}:{},...d.preferredAlternatives&&d.preferredAlternatives.length>0?{preferredAlternatives:[...d.preferredAlternatives]}:{},...d.replacementTarget?{replacementTarget:d.replacementTarget}:{},warningMessage:I}}function $(d){let I=[],M={...d.applicability.computedResponseRule?{computedResponseRule:d.applicability.computedResponseRule}:{},kind:"rewrite_output_slot",...d.applicability.exactFragments?{exactFragments:d.applicability.exactFragments}:{},...d.applicability.pathTemplate?{pathTemplate:d.applicability.pathTemplate}:{},...d.applicability.preferredAlternatives&&d.applicability.preferredAlternatives.length>0?{preferredAlternatives:d.applicability.preferredAlternatives}:{},...d.applicability.preferredFragments&&d.applicability.preferredFragments.length>0?{preferredFragments:d.applicability.preferredFragments}:{},...d.applicability.replacementPairs&&d.applicability.replacementPairs.length>0?{replacementPairs:d.applicability.replacementPairs}:{},...d.applicability.urlTemplate?{urlTemplate:d.applicability.urlTemplate}:{}};if(M.computedResponseRule||M.exactFragments||M.pathTemplate||M.preferredAlternatives||M.preferredFragments||M.replacementPairs||M.urlTemplate)I.push(M);if(d.applicability.forbiddenFragments&&d.applicability.forbiddenFragments.length>0)I.push({forbiddenFragments:[...d.applicability.forbiddenFragments],kind:"block_surface",...d.applicability.replacementPairs&&d.applicability.replacementPairs.length>0?{replacementPairs:d.applicability.replacementPairs}:{}});if(d.applicability.guardedBehavior)I.unshift({...d.applicability.guardedBehavior.allowedWhen?{allowedWhen:d.applicability.guardedBehavior.allowedWhen}:{},fallbackBehavior:d.applicability.guardedBehavior.fallbackBehavior,kind:"require_precondition_check",precondition:d.applicability.guardedBehavior.precondition,...d.applicability.guardedBehavior.subject?{subject:d.applicability.guardedBehavior.subject}:{}});else{let E=dI({backupMention:d.applicability.backupMention,fallbackInstruction:d.applicability.fallbackInstruction,preferredAlternatives:d.applicability.preferredAlternatives,replacementTarget:nd(d.applicability.preferredAlternatives)});if(E&&(d.behavioralKind==="avoidance"||d.behavioralKind==="preference"||d.behavioralKind==="transformation_rule"||E.preferredAlternatives&&E.preferredAlternatives.length>0||E.backupMention||E.replacementTarget))I.push({...E.backupMention?{backupMention:E.backupMention}:{},kind:"require_warning",...d.applicability.pathTemplate?{pathTemplate:d.applicability.pathTemplate}:{},...E.preferredAlternatives?{preferredAlternatives:E.preferredAlternatives}:{},...E.replacementTarget?{replacementTarget:E.replacementTarget}:{},...d.applicability.urlTemplate?{urlTemplate:d.applicability.urlTemplate}:{},warningMessage:E.warningMessage})}return I.length>0?{concise:!0,operations:I}:void 0}function II(d){return d.formatRule}function o(d){return d.negativeRule}function EI(d){return d.firstActionName!==void 0}function MI(d){return d.firstActionName}function RI(d){return d.generalRule}function SI(d){let I=d.match(/\b([A-Z][A-Za-z0-9_]*)\(n\)\s*=\s*([^.\n]+?)(?:\.|\n|$)/u);if(I?.[1]&&I[2]){let E=I[1].trim(),R=I[2].trim(),S=[...d.matchAll(new RegExp(`${b(E)}\\((-?\\d+)\\)\\s*=\\s*(-?\\d+(?:\\.\\d+)?)`,"gu"))].map((P)=>{let k=Number(P[1]),O=Number(P[2]);if(!Number.isInteger(k)||!Number.isFinite(O))return;return{index:k,value:O}}).filter((P)=>Boolean(P));return{...S.length>0?{baseCases:S}:{},expression:R,kind:"recurrence",sequenceName:E}}let M=d.match(/\b([a-z])\s*([⊗⊕⊖Ω])\s*([a-z])\s*=\s*([^.\n]+?)(?:\.|\n|$)/u);if(M?.[1]&&M[2]&&M[3]&&M[4])return{expression:M[4].trim(),kind:"binary_operator",leftVariable:M[1].trim(),operatorSymbol:M[2].trim(),rightVariable:M[3].trim()};return}function PI(d){let I=d.language??w,M=d.languageContext??I.resolveFromText({text:d.rule}),E=I.analyzeBehavioralRule(d.rule,M),R=RI(E),S=ed({exemplarCount:d.exemplarCount,hasGeneralRuleMarker:R}),P=E.triggerPhrases,k=W(d.appliesTo),O=E.protocolRewrite?id(E.protocolRewrite):null,s=E.directoryRestriction?pd(E.directoryRestriction):null,G=E.filetypeReplacement?ad(E.filetypeReplacement):null,Q=E.distrustRouting?ud(E.distrustRouting):null,j=E.exactAction?r(E.exactAction):void 0,H=SI(d.rule),C=X([...E.preferredAlternatives??[],...Q?.preferredAlternatives??[]]),x=E.guard?td(E.guard):void 0,D=X([...E.triggerPhrases??[],...x?.check?[x.check]:[],...x?.subject?[x.subject]:[],...O?.queryContains??[],...Q?.queryContains??[]]),c=E.backupRequested?"Mention a safe backup before proceeding.":void 0,K=X([...E.forbiddenFragments??[],...O?.forbiddenFragments??[],...s?.forbiddenFragments??[],...G?.forbiddenFragments??[],...Q?.forbiddenFragments??[]]),U=X([...E.preferredFragments??[],...O?.preferredFragments??[],...s?.preferredFragments??[],...G?.preferredFragments??[]]),Y=s?.pathTemplate,N=Cd([...O?.replacementPairs??[],...G?.replacementPairs??[]]),Z=O?.urlTemplate,J=x?.fallbackInstruction??Q?.fallbackInstruction??O?.fallbackInstruction??s?.fallbackInstruction??(C.length>0&&o(E)?`Prefer ${C.join(" or ")}${c?" and mention a safe backup before proceeding":""} or warn instead of implying the avoided behavior.`:void 0),L=x?{...x.allowedStates?{allowedWhen:x.allowedStates}:{},fallbackBehavior:{...c?{backupMention:c}:{},...C.length>0?{preferredAlternatives:C}:{},...C[0]?{replacementTarget:C[0]}:{},warningMessage:x.fallbackInstruction??"Warn or defer instead of assuming the required precondition already passed."},precondition:x.check,...x.subject?{subject:x.subject}:{}}:void 0;if(j||EI(E)){let _=MI(E),m=E.argumentOrder;return{behavioralKind:o(E)||d.kind==="dont"?"first_action":"syntax_constraint",enactmentSurface:"host_action",applicability:{appliesTo:k,...j?{canonicalFirstAction:j}:_?{canonicalFirstAction:{kind:_.includes("_")?"tool_call":"command",name:_}}:{},...m?{argumentOrder:m}:{},...P&&!j?{queryContains:P}:{}},transferMode:S==="general"?"pattern_bounded":S}}if(II(E)){let{formatPrefix:_,formatSuffix:m}=E,F=X([...(E.requiredFragments??[]).filter((Ud)=>Ud!==m),_,m]);return{behavioralKind:"format_contract",enactmentSurface:"text_response",applicability:{appliesTo:k,exactFragments:{..._?{prefixes:[_]}:{},...F.length>0?{required:F}:{},...m?{suffixes:[m]}:{}},...P?{queryContains:P}:{},textResponsePlan:$({behavioralKind:"format_contract",applicability:{appliesTo:k,exactFragments:{..._?{prefixes:[_]}:{},...F.length>0?{required:F}:{},...m?{suffixes:[m]}:{}},...P?{queryContains:P}:{}}})},transferMode:S}}if(d.kind==="prefer"){let _={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"preference",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"preference",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"preference",applicability:_})}:{}},transferMode:S}}if(d.kind==="dont"||o(E)){let _={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"avoidance",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"avoidance",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"avoidance",applicability:_})}:{}},transferMode:S}}if(d.kind==="do"&&!P){let _={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"transformation_rule",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})}:{}},transferMode:R?"general":"pattern_bounded"}}if(R||(d.exemplarCount??0)>=2){let _={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"transformation_rule",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})}:{}},transferMode:R?"general":"pattern_bounded"}}let y={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:"exemplar_fact",enactmentSurface:"text_response",applicability:{...y,...$({behavioralKind:"exemplar_fact",applicability:y})?{textResponsePlan:$({behavioralKind:"exemplar_fact",applicability:y})}:{}},transferMode:"example_only"}}function z(d,I){if(!I||I.length===0)return[];let M=T(d);return I.filter((E)=>M.includes(T(E)))}function Cd(d){let I=[],M=new Set;for(let E of d){if(!E)continue;let R=`${E.from}\x00${E.to}`;if(M.has(R))continue;M.add(R),I.push(E)}return I}function kI(d){if(!d.transientFeedback||d.transientFeedback.length===0)return[];let I=W(d.appliesTo),M=T(d.query),E=[];for(let R of d.transientFeedback){if(R.lifecycle!=="active"||R.kind==="validated_pattern")continue;if(sd(R))continue;let S=PI({appliesTo:R.appliesTo,exemplarCount:1,kind:R.kind,rule:R.rule});if(S.enactmentSurface!==d.surface)continue;let P=W(S.applicability.appliesTo??R.appliesTo),k=P===I;if(!k&&P!=="general_response")continue;let O=X([...z(M,S.applicability.queryContains),...z(M,S.applicability.actionSummaryContains),...z(M,S.applicability.forbiddenFragments),...z(M,S.applicability.preferredFragments)]),s=O.length===0&&(d.surface==="text_response"?f(S):Yd(S))&&(S.applicability.queryContains?.length??0)===0;if(S.transferMode!=="general"&&O.length===0&&!s)continue;let G=(k?1e4:0)+Rd[S.behavioralKind]*100+Sd[S.transferMode]*10+O.length+(s?3:0)+5;E.push({feedback:R,matchedQueryTokens:O,policy:S,score:G})}return E}function iI(d){let I=W(d.appliesTo),M=T(d.query),E=[];for(let S of d.feedback??[]){if(S.lifecycle!=="active")continue;let P=sd(S);if(!P||P.enactmentSurface!==d.surface)continue;let k=W(P.applicability.appliesTo??S.appliesTo),O=k===I;if(!O&&k!=="general_response")continue;let s=X([...z(M,P.applicability.queryContains),...z(M,P.applicability.actionSummaryContains),...z(M,P.applicability.forbiddenFragments),...z(M,P.applicability.preferredFragments)]);if(P.transferMode==="example_only"&&s.length===0)continue;let G=(O?1e4:0)+(d.surface==="host_action"&&P.enactmentSurface==="host_action"?2000:0)+Rd[P.behavioralKind]*100+Sd[P.transferMode]*10+s.length;E.push({feedback:S,matchedQueryTokens:s,policy:P,score:G})}let R=kI(d);return[...E,...R].sort((S,P)=>P.score-S.score)}function OI(d){let I=new Set,M=[];for(let E of d){let R=JSON.stringify(E);if(I.has(R))continue;I.add(R),M.push(E)}return M}function pI(d){return xI(d.map((I)=>I.policy))}function xI(d){let I=OI(d.flatMap((R)=>{if(R.enactmentSurface!=="text_response")return[];return R.applicability.textResponsePlan?.operations??$({behavioralKind:R.behavioralKind,applicability:R.applicability})?.operations??[]}));if(I.length===0)return;let M=d.some((R)=>R.applicability.textResponsePlan?.brevityOnly===!0);return{...d.some((R)=>R.applicability.textResponsePlan?.bulletOnly===!0)?{bulletOnly:!0}:{},...M?{brevityOnly:!0}:{},concise:!0,operations:I}}function _I(d){switch(d.kind){case"rewrite_output_slot":return[d.computedResponseRule?d.computedResponseRule.kind==="recurrence"?`rewrite_output_slot recurrence_rule: ${d.computedResponseRule.sequenceName}(n) = ${d.computedResponseRule.expression}`:`rewrite_output_slot binary_rule: ${d.computedResponseRule.leftVariable} ${d.computedResponseRule.operatorSymbol} ${d.computedResponseRule.rightVariable} = ${d.computedResponseRule.expression}`:void 0,d.replacementPairs&&d.replacementPairs.length>0?`rewrite_output_slot replacements: ${d.replacementPairs.map((I)=>`${I.from} -> ${I.to}`).join(", ")}`:void 0,d.urlTemplate?`rewrite_output_slot url_template: keep ${d.urlTemplate.scheme}://${d.urlTemplate.host} and place the requested page after the host as a path segment`:void 0,d.pathTemplate?`rewrite_output_slot path_template: keep safe anchor ${d.pathTemplate.anchor} and preserve the requested filename`:void 0,d.exactFragments?.prefixes?.length?`rewrite_output_slot prefix: ${d.exactFragments.prefixes[0]}`:void 0,d.exactFragments?.suffixes?.length?`rewrite_output_slot suffix: ${d.exactFragments.suffixes[0]}`:void 0].filter((I)=>Boolean(I));case"block_surface":return[`block_surface forbidden: ${d.forbiddenFragments.join(", ")}`,d.fallbackAnswer?`block_surface fallback: ${d.fallbackAnswer}`:void 0].filter((I)=>Boolean(I));case"require_warning":return[`require_warning: ${d.warningMessage}`,d.preferredAlternatives&&d.preferredAlternatives.length>0?`warning_alternatives: ${d.preferredAlternatives.join(", ")}`:void 0,d.backupMention?`warning_backup: ${d.backupMention}`:void 0].filter((I)=>Boolean(I));case"require_precondition_check":return[`require_precondition_check: ${d.precondition}`,d.allowedWhen&&d.allowedWhen.length>0?`allowed_when: ${d.allowedWhen.join(" or ")}`:void 0,`fallback_behavior: ${d.fallbackBehavior.warningMessage}`].filter((I)=>Boolean(I))}}function nI(d){if(!d)return[];return X([...d.brevityOnly?["brevity_only: emit only the answer surface with no extra explanation"]:[],...d.bulletOnly?["bullet_only: emit a terse bullet list with no paragraph preface"]:[],...d.operations.flatMap((I)=>_I(I))])}function b(d){return d.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Ld(d){return Number.isInteger(d)?String(d):String(Number(d.toFixed(10)))}function Gd(d){let I=d.expression.replace(/\^/gu,"**");for(let[M,E]of Object.entries(d.scope).sort(([R],[S])=>S.length-R.length))I=I.replace(new RegExp(`\\b${b(M)}\\b`,"gu"),`(${E})`);if(/[^0-9+\-*/().\s*]/u.test(I))return;try{let M=Function(`"use strict"; return (${I});`)();return typeof M==="number"&&Number.isFinite(M)?M:void 0}catch{return}}function sI(d){let I=new Map;for(let M of d.query.matchAll(new RegExp(`${b(d.sequenceName)}\\((-?\\d+)\\)\\s*=\\s*(-?\\d+(?:\\.\\d+)?)`,"gu"))){let E=Number(M[1]),R=Number(M[2]);if(!Number.isInteger(E)||!Number.isFinite(R))continue;I.set(E,R)}return I}function CI(d){let I=d.query.match(new RegExp(`${b(d.rule.sequenceName)}\\((-?\\d+)\\)(?!\\s*=)`,"u"));if(!I?.[1])return;let M=Number(I[1]);if(!Number.isInteger(M))return;let E=new Map;for(let O of d.rule.baseCases??[])E.set(O.index,O.value);for(let[O,s]of sI({query:d.query,sequenceName:d.rule.sequenceName}))E.set(O,s);let R=new Set,S=new RegExp(`${b(d.rule.sequenceName)}\\(n\\s*([+-])\\s*(\\d+)\\)`,"gu"),P=(O)=>{if(E.has(O))return E.get(O);if(R.has(O))return;R.add(O);let s=d.rule.expression.replace(S,(Q,j,H)=>{let C=Number(H);if(!Number.isInteger(C))return"NaN";let x=j==="+"?O+C:O-C,D=P(x);return D===void 0?"NaN":`(${D})`});s=s.replace(/\bn\b/gu,`(${O})`);let G=Gd({expression:s,scope:{}});if(R.delete(O),G===void 0)return;return E.set(O,G),G},k=P(M);return k===void 0?void 0:Ld(k)}function LI(d){let I=d.query.match(new RegExp(`(-?\\d+(?:\\.\\d+)?)\\s*${b(d.rule.operatorSymbol)}\\s*(-?\\d+(?:\\.\\d+)?)`,"u"));if(!I?.[1]||!I[2])return;let M=Number(I[1]),E=Number(I[2]);if(!Number.isFinite(M)||!Number.isFinite(E))return;let R=Gd({expression:d.rule.expression,scope:{[d.rule.leftVariable]:M,[d.rule.rightVariable]:E}});return R===void 0?void 0:Ld(R)}function dE(d){if(!d.query||!d.rule)return;switch(d.rule.kind){case"recurrence":return CI({query:d.query,rule:d.rule});case"binary_operator":return LI({query:d.query,rule:d.rule})}}function q(d){if(d.startsWith("~/")){let I=d.slice(2).split("/").filter(Boolean);return I.length>0?`|~|${I.join("|")}|`:"|~|"}if(d.startsWith("/")){let I=d.split("/").filter(Boolean);return I.length>0?`|${I.join("|")}|`:"|/|"}return`|${d}|`}function gd(d){if(!d)return;return(B(d)?.namedTarget??jd(d)[0])?.trim().replace(/[.,;:!?]+$/u,"")}function GI(d){if(!d)return;let I=B(d),M=I?.pathBase,E=I?.namedTarget,R=M?.replace(/[.,;:!?]+$/u,""),S=E?.replace(/[.,;:!?]+$/u,"");if(R){let k=R.endsWith("/")?`${R}${S??""}`.replace(/\/+$/u,""):S?`${R}/${S}`:R;return q(k)}let P=gd(d);return P?q(P):void 0}function v(d){return jd(d??"")[0]?.trim()}function gI(d,I){let M=v(d);if(!M)return;let R=/_<token>|<token>_/u.test(I??"")?M.replace(/[^A-Za-z0-9]+/gu,"_").replace(/^_+|_+$/gu,""):M.replace(/[^A-Za-z0-9]/gu,"");return R&&R.length>0?R:void 0}function AI(d){if(!d)return;return B(d)?.structuredTerms?.join(" ")}function Ad(d){if(!d)return;return B(d)?.comparison?.field}function Dd(d){return B(d)?.comparison?.operator}function DI(d){if(/^-?\d+(?:\.\d+)?$/u.test(d))return d;if(/^['"].*['"]$/u.test(d))return d;return`'${d}'`}function cI(d){return d.replace(/^['"]|['"]$/gu,"").replace(/[.,;:!?]+$/u,"")}function cd(d){if(!d)return;let I=B(d)?.comparison?.value;if(I)return DI(cI(I));return}function jI(d,I){if(!I)return;let M=d.match(/^(.+\|\s*FILTER\s+)[A-Za-z_][A-Za-z0-9_.-]*\s*(?:>=|<=|=|>|<)\s*.+$/iu);if(!M?.[1])return;let E=Ad(I),R=Dd(I),S=cd(I);if(!E||!R||!S)return;return`${M[1]}${E} ${R} ${S}`}function HI(d,I){let M=d;if(M.includes("|folder|")){let E=gd(I);if(!E)return;M=M.replace(/\|folder\|/gu,q(E))}if(M.includes("|path|")){let E=GI(I);if(!E)return;M=M.replace(/\|path\|/gu,E)}if(M.includes("<filename>")){let E=v(I);if(!E)return;M=M.replace(/<filename>/gu,E)}if(M.includes("<id>")){let E=v(I);if(!E)return;M=M.replace(/<id>/gu,E)}if(M.includes("<item>")){let E=v(I);if(!E)return;M=M.replace(/<item>/gu,E)}if(M.includes("<qty>")){let E=I?.match(/\bqty\b[^0-9]*([0-9]+)/iu)?.[1]??I?.match(/\b([0-9]+)\b/u)?.[1];if(!E)return;M=M.replace(/<qty>/gu,E)}if(M.includes("<terms>")){let E=AI(I);if(!E)return;M=M.replace(/<terms>/gu,E)}if(M.includes("<token>")){let E=gI(I,M);if(!E)return;M=M.replace(/<token>/gu,E)}if(M.includes("<field>")){let E=Ad(I);if(!E)return;M=M.replace(/<field>/gu,E)}if(M.includes("<operator>")){let E=Dd(I);if(!E)return;M=M.replace(/<operator>/gu,E)}if(M.includes("<value>")){let E=cd(I);if(!E)return;M=M.replace(/<value>/gu,E)}return/<[^>]+>/u.test(M)?void 0:M}function V(d){return`'${d.replaceAll("'","\\'")}'`}function NI(d){return d.endsWith("/")}function UI(d,I){if(!NI(d))return d;let M=I.split("/").filter(Boolean).at(-1);return M?`${d}${M}`:d}function KI(d){let I=T(d.argumentLabel),M=d.sourcePaths[d.usedSourceCount];if(I.includes("action")){let E=d.hostAction.verb;return E?V(E):void 0}if(I.includes("owner")){let E=d.hostAction.owner;return E?V(E):void 0}if(I.includes("permission")||I.includes("perms")){let E=d.hostAction.permissions;return E?V(E):void 0}if(I.includes("compression")){let E=d.hostAction.compression;return E?V(E):void 0}if(I.includes("flags")){let E=d.hostAction.flags??[];if(E.length===0)return;return`[${E.map((R)=>V(R)).join(",")}]`}if(I.includes("tag")){let E=d.hostAction.tag;return E?V(E):void 0}if(I.includes("mode")){let E=d.hostAction.mode;return E?V(E):void 0}if(I.includes("sources")){if(d.sourcePaths.length===0)return;return`[${d.sourcePaths.map((E)=>V(E)).join(",")}]`}if(I.includes("source"))return M?V(M):void 0;if(I.includes("destination")||I.includes("target")||I.includes("archive")){let E=d.destinationPath;if(!E)return;let R=d.sourcePaths[0],S=/\b(?:directory|folder|root)\b/iu.test(I)||/(?:^|_)dir(?:_|$)/iu.test(I);return V(R&&!S?UI(E,R):E)}return}function n(d,I){let M=d.applicability.canonicalFirstAction;if(M?.kind!=="tool_call"||!M.name||!M.args||M.args.length===0)return M;let E=B(I)?.hostAction;if(!E)return M;let R=E.sources??[],S=E.destination,P=[],k=0;for(let O of M.args){let s=KI({argumentLabel:O,destinationPath:S,hostAction:E,sourcePaths:R,usedSourceCount:k});if(!s)return M;P.push(s);let G=T(O);if(G.includes("source")&&!G.includes("sources"))k+=1}return{args:P,kind:"tool_call",name:M.name,raw:`${M.name}(${P.join(", ")})`}}function IE(d){let I=[];for(let{feedback:M,policy:E}of d){if(E.enactmentSurface!=="text_response")continue;if(E.behavioralKind==="format_contract"){let R=E.applicability.exactFragments?.prefixes??[],S=E.applicability.exactFragments?.required??[],P=E.applicability.exactFragments?.suffixes??[];if(R.length>0)I.push(`Start the response with "${R[0]}".`);for(let k of S)I.push(`Include the exact fragment "${k}".`);if(P.length>0)I.push(`End the response with "${P[0]}".`);if(M.rule)I.push(`Follow this exact formatting rule: ${M.rule}`);continue}for(let R of E.applicability.replacementPairs??[])I.push(`If the answer would contain "${R.from}", rewrite it to "${R.to}" instead of emitting the disallowed form.`);for(let R of E.applicability.forbiddenFragments??[])I.push(`Do not emit the exact fragment "${R}" in the final answer unless directly quoting user input.`);for(let R of E.applicability.preferredFragments??[])I.push(`Prefer a safe replacement fragment such as "${R}" when the current probe matches.`);if(E.applicability.urlTemplate){let{urlTemplate:R}=E.applicability;I.push(`When answering with a URL, keep the established origin "${R.scheme}://${R.host}" and place the requested page after the host as a path segment, for example "${R.example}".`),I.push("Do not rewrite the requested page into a subdomain when the learned URL pattern uses a path after the host.")}if(E.applicability.pathTemplate){let{pathTemplate:R}=E.applicability;I.push(`When redirecting a file path, keep the established safe directory anchor "${R.anchor}" and preserve the requested filename under that directory, for example "${R.example}".`),I.push("Do not invent a new top-level directory when the learned safe path already provides a concrete user-writable location.")}if(E.applicability.guard){let{guard:R}=E.applicability,S=R.subject?`"${R.subject}"`:"the guarded behavior";if(I.push(`Before using or implying ${S}, ${R.check}.`),(R.allowedStates?.length??0)>0)I.push(`Only proceed when the required check resolves to ${R.allowedStates.join(" or ")}.`);if(R.fallbackInstruction)I.push(R.fallbackInstruction)}if((E.applicability.preferredAlternatives?.length??0)>0)I.push(`Prefer ${E.applicability.preferredAlternatives.map((R)=>`"${R}"`).join(" or ")} as the safer replacement behavior when the trigger matches.`);if(E.applicability.fallbackInstruction)I.push(E.applicability.fallbackInstruction);if(f(E))I.push("If a short compliant answer, redirect, or warning already satisfies the request, stop there instead of expanding into a longer response.");if(E.behavioralKind==="transformation_rule"){if(M.rule&&!f(E))I.push(`Apply this rule only when it matches the current probe: ${M.rule}`);continue}if(E.behavioralKind==="preference"){if(M.rule&&!f(E))I.push(`Prefer this behavior when it fits the current probe: ${M.rule}`);continue}if(E.behavioralKind==="avoidance"){if(M.rule&&!f(E))I.push(`Avoid this behavior when the trigger matches: ${M.rule}`);continue}if(E.behavioralKind==="exemplar_fact"&&M.rule){I.push(`Treat this as example-bound guidance unless the probe clearly matches: ${M.rule}`);continue}}return X(I)}function jd(d){return[...d.matchAll(/(?<![\p{L}\p{N}_/])(['"`])([^'"`]+)\1(?![\p{L}\p{N}_/])/gu)].map((I)=>I[2]?.trim()).filter((I)=>Boolean(I))}function dd(d){let I=B(d.query)?.hostAction,M=I?.sources?.[0],E=I?.destination;if(!M||!E)return;if(E.endsWith("/")){let R=M.split("/").filter(Boolean).at(-1);if(R)E=`${E}${R}`}return{args:[`'${E}'`,`'${M}'`],kind:"tool_call",name:d.name,raw:`${d.name}('${E}', '${M}')`}}function $I(d,I){let M=d.applicability.canonicalFirstAction;if(M?.raw){let S=HI(M.raw,I);if(S){let P=r(jI(S,I)??S);if(I&&P?.kind==="tool_call"&&(d.applicability.argumentOrder??[]).length>=2&&/(?:destination|target|archive)/iu.test(T(d.applicability.argumentOrder?.[0]))&&T(d.applicability.argumentOrder?.[1]).includes("source"))return dd({name:P.name,query:I})??P;if(I&&P?.kind==="tool_call"&&P.args&&P.args.every((k)=>/^[a-z_][a-z0-9_]*$/iu.test(k)))return n({...d,applicability:{...d.applicability,canonicalFirstAction:P}},I);return P}if(/<[^>]+>|\|(?:folder|path)\|/u.test(M.raw))return;return M}if(!M?.name||!I)return M;let E=M.name.trim();if(M.kind==="tool_call"&&M.args&&M.args.every((S)=>/^[a-z_][a-z0-9_]*$/iu.test(S)))return n(d,I);let R=d.applicability.argumentOrder??[];if(R.length<2||!/(?:destination|target|archive)/iu.test(T(R[0]))||!T(R[1]).includes("source"))return M;return dd({name:E,query:I})??M}function EE(d){let I=r(d.template);if(!I)return;return $I({behavioralKind:"first_action",enactmentSurface:"host_action",applicability:{appliesTo:"general_response",canonicalFirstAction:I},transferMode:"pattern_bounded"},d.query)?.raw??I.raw}var RE="session_archives",SE="experiences",PE="learning_proposals",kE="promotion_records";function XI(d,I){return d??I??new Date(0).toISOString()}function OE(d){let I=XI(d.createdAt,d.archivedAt);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,sourceSessionIds:d.sourceSessionIds??[d.sessionId],summary:d.summary,normalizedTranscript:d.normalizedTranscript,keyDecisions:d.keyDecisions??[],unresolvedItems:d.unresolvedItems??[],referencedArtifacts:d.referencedArtifacts??[],scopeLineage:d.scopeLineage??[],locale:d.locale,createdAt:I,archivedAt:d.archivedAt??I}}function xE(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,kind:d.kind,traceId:d.traceId,sourceTraceIds:d.sourceTraceIds??[d.traceId],trigger:d.trigger??"api",modelInfluence:d.modelInfluence??"none",summary:d.summary,outcome:d.outcome??"success",policyApplied:d.policyApplied??[],metrics:d.metrics??{},linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],linkedProposalIds:d.linkedProposalIds??[],...d.metadata?{metadata:d.metadata}:{},createdAt:d.createdAt??new Date(0).toISOString()}}function _E(d){let I=d.createdAt??new Date(0).toISOString();return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,proposalType:d.proposalType,status:d.status??"pending",traceId:d.traceId,summary:d.summary,rationale:d.rationale,sourceExperienceIds:d.sourceExperienceIds??[],linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],modelInfluence:d.modelInfluence??"none",createdAt:I,updatedAt:d.updatedAt??I}}function sE(d){let I=d.decidedAt??d.createdAt??new Date(0).toISOString();return{id:d.id,proposalId:d.proposalId,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,traceId:d.traceId,decision:d.decision,summary:d.summary,rationale:d.rationale,sourceExperienceIds:d.sourceExperienceIds??[],linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],policyOutcome:d.policyOutcome??"not_run",verificationOutcome:d.verificationOutcome??"not_run",evalOutcome:d.evalOutcome??"not_run",createdAt:d.createdAt??I,decidedAt:I}}var Hd=Symbol.for("goodmemory.eval.support");function gE(d,I){return d[Hd]=I,d}function AE(d){return d[Hd]}var Nd=Symbol.for("goodmemory.integration.support");function cE(d,I){return d[Nd]=I,d}function jE(d){return d[Nd]}
export{Kd as Ja,YI as Ka,ZI as La,W as Ma,JI as Na,VI as Oa,TI as Pa,mI as Qa,QI as Ra,WI as Sa,zI as Ta,BI as Ua,bI as Va,FI as Wa,hI as Xa,vI as Ya,Td as Za,aI as _a,uI as $a,tI as ab,SI as bb,PI as cb,iI as db,pI as eb,xI as fb,nI as gb,dE as hb,IE as ib,EE as jb,oI as kb,wI as lb,qI as mb,RE as nb,SE as ob,PE as pb,kE as qb,OE as rb,xE as sb,_E as tb,sE as ub,gE as vb,AE as wb,cE as xb,jE as yb};
import{Jb as T$,Lb as I$,Mb as N$,Nb as w$,Ob as W$,Pb as y$,Qb as f$,Rb as S$,Tb as X$}from"./chunk-g26g591p.js";import{Wb as b,Xb as L$}from"./chunk-c28647f0.js";import{bc as m$}from"./chunk-eqpe4gcb.js";import{Database as g$}from"bun:sqlite";import{Buffer as Y4}from"node:buffer";import{mkdirSync as Z4}from"node:fs";import{dirname as W4}from"node:path";import{spawnSync as s$}from"node:child_process";import{existsSync as o$}from"node:fs";var e={};m$(e,{loadVss:()=>_$,loadVector:()=>z$,load:()=>l$,getVssLoadablePath:()=>U$,getVectorLoadablePath:()=>O$});import{join as b$}from"node:path";import{fileURLToPath as p$}from"node:url";import{arch as t,platform as o}from"node:process";import{statSync as u$}from"node:fs";var A$=[["darwin","x64"],["darwin","arm64"],["linux","x64"]];function r$($,G){return A$.find(([Y,X])=>$==Y&&G===X)!==null}function c$($){if($==="win32")return"dll";if($==="darwin")return"dylib";return"so"}function d$($,G){return`sqlite-vss-${$==="win32"?"windows":$}-${G}`}function B$($){if(!r$(o,t))throw Error(`Unsupported platform for sqlite-vss, on a ${o}-${t} machine, but not in supported platforms (${A$.map(([X,H])=>`${X}-${H}`).join(",")}). Consult the sqlite-vss NPM package README for details. `);let G=d$(o,t),Y=b$(p$(new URL(".",import.meta.url)),"..","..",G,"lib",`${$}.${c$(o)}`);if(!u$(Y,{throwIfNoEntry:!1}))throw Error(`Loadble extension for sqlite-vss not found. Was the ${G} package installed? Avoid using the --no-optional flag, as the optional dependencies for sqlite-vss are required.`);return Y}function O$(){return B$("vector0")}function U$(){return B$("vss0")}function z$($){$.loadExtension(O$())}function _$($){$.loadExtension(U$())}function l$($){z$($),_$($)}var G$="vss_inner_product",K$=Symbol.for("goodmemory.sqlite.library-registry"),i$=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/usr/lib/x86_64-linux-gnu/libsqlite3.so","/usr/lib/aarch64-linux-gnu/libsqlite3.so","/usr/lib64/libsqlite3.so","/usr/lib/libsqlite3.so"],n$=`
import { Database } from "bun:sqlite";
const [customLibraryPath, vectorPath, vssPath] = process.argv.slice(1);
if (!customLibraryPath || !vectorPath || !vssPath) {
throw new Error("Missing sqlite-vss probe paths.");
}
Database.setCustomSQLite(customLibraryPath);
const database = new Database(":memory:", { strict: true });
try {
database.loadExtension(vectorPath);
database.loadExtension(vssPath);
database.query("select vss_version() as version").get();
database.exec(
"CREATE VIRTUAL TABLE __goodmemory_vss_probe USING vss0(embedding(3)); DROP TABLE __goodmemory_vss_probe;",
);
} finally {
database.close();
}
`;function m($){if(!$)return;let G=$.trim();return G.length>0?G:void 0}function a$($){let G=m($);if(!G)return[];return G.split(",").map((Y)=>Y.trim()).filter((Y)=>Y.length>0)}function t$($){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION: ${$}. Expected a valid SQLite function identifier.`);return $}function e$($){let G=m($);if(!G)return;if(G==="off"||G==="prefer"||G==="require")return G;throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_MODE: ${G}. Expected off|prefer|require.`)}function $$($){let{backend:G,customLibraryPath:Y,entryPoint:X,mode:H,path:F,paths:W,searchFunction:B}=$;return{customLibraryPath:Y,vectorExtension:{backend:G,entryPoint:X,mode:H,path:F,paths:W,searchFunction:B}}}function F$($){return{config:$$({backend:"none",customLibraryPath:$.customLibraryPath,entryPoint:void 0,mode:"off",path:void 0,paths:[],searchFunction:$.searchFunction}),diagnostics:{available:$.source==="disabled",backend:"none",effectiveMode:"off",reason:$.reason,requestedMode:$.requestedMode,source:$.source}}}function $4($){let G=s$(process.execPath,["-e",n$,"--",$.customLibraryPath,...$.paths],{encoding:"utf8",timeout:1e4});if(G.error)return{loadable:!1,reason:G.error.message};if(G.status!==0)return{loadable:!1,reason:`${G.stdout}${G.stderr}`.trim()||`sqlite-vss probe exited with status ${G.status}`};return{loadable:!0}}function G4($={}){let G=$.exists??o$,Y=($.libraryCandidatePaths??i$).find((X)=>G(X));if(!Y)return{runtime:null};try{let X=e,H=Object.hasOwn($,"getVectorLoadablePath")?$.getVectorLoadablePath:X.getVectorLoadablePath,F=Object.hasOwn($,"getVssLoadablePath")?$.getVssLoadablePath:X.getVssLoadablePath;if(!H||!F)return{runtime:null};let W=H(),B=F();if(!G(W)||!G(B))return{runtime:null};let M={customLibraryPath:Y,paths:[W,B]},E=($.probeRuntime??$4)(M);if(!E.loadable)return{runtime:null,unavailableReason:E.reason??"Bundled sqlite-vss runtime probe failed."};return{runtime:M}}catch(X){return{runtime:null,unavailableReason:`Failed to inspect bundled sqlite-vss runtime: ${X instanceof Error?X.message:String(X)}`}}}function M$($=process.env,G){let Y=m($.GOODMEMORY_SQLITE_CUSTOM_LIBRARY_PATH),X=m($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),H=a$($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),F=e$($.GOODMEMORY_SQLITE_VECTOR_MODE),W=t$(m($.GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION)??G$),B=m($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_ENTRYPOINT),M=G?.inspectBundledSQLiteVssRuntime?G.inspectBundledSQLiteVssRuntime():G?.detectBundledSQLiteVssRuntime?{runtime:G.detectBundledSQLiteVssRuntime()}:G4(),E=M.runtime,C=M.unavailableReason,U=F??(H.length>0||E||C?"prefer":"off");if(U==="off")return F$({customLibraryPath:Y,requestedMode:U,searchFunction:W,source:"disabled"});if(H.length>0)return{config:$$({backend:"sql-function",customLibraryPath:Y,entryPoint:B,mode:U,path:X,paths:H,searchFunction:W}),diagnostics:{available:!0,backend:"sql-function",effectiveMode:U,requestedMode:U,source:"env"}};if(E){let q=U==="require"?"require":"prefer";return{config:$$({backend:"sqlite-vss",customLibraryPath:Y??E.customLibraryPath,entryPoint:B,mode:q,path:E.paths.join(","),paths:E.paths,searchFunction:W}),diagnostics:{available:!0,backend:"sqlite-vss",effectiveMode:q,requestedMode:U,source:"bundled-sqlite-vss"}}}return F$({customLibraryPath:Y,requestedMode:U,searchFunction:W,source:"unavailable",reason:C??"SQLite vector acceleration was requested, but no supported sqlite-vss runtime assets were detected and no manual GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH was configured."})}function q$($,G){if(!$.customLibraryPath)return;let Y=globalThis,X=Y[K$]??{configuredPaths:new WeakMap};Y[K$]=X;let H=X.configuredPaths.get(G);if(H===$.customLibraryPath)return;if(H)throw Error(`SQLite runtime already uses ${H} and cannot switch to ${$.customLibraryPath}.`);G.setCustomSQLite($.customLibraryPath),X.configuredPaths.set(G,$.customLibraryPath)}function D$($,G){if($.mode==="off"||!($.paths?.length??0))return{loaded:!1,reason:"SQLite vector acceleration is disabled."};try{for(let Y of $.paths)G.loadExtension(Y,$.entryPoint);return{loaded:!0}}catch(Y){let X=Y instanceof Error?Y.message:String(Y);if($.mode==="prefer")return{loaded:!1,reason:`Failed to load SQLite vector extension at ${$.path}: ${X}`};throw Error(`Failed to load SQLite vector extension at ${$.path}: ${X}`)}}var i=null,Y$=null,Q$="document_filter_indexes",k$="document_text_fts_keys",P$=2,E$=2;function X4(){if(!i)i={customLibraryPath:x$().config.customLibraryPath},q$(i,g$);return i}function x$(){if(!Y$)Y$=M$();return Y$}function H4($,G){if(G?.readOnly||$===":memory:")return;Z4(W4($),{recursive:!0})}function H$($,G){return X4(),H4($,G),new g$($,{create:G?.readOnly?!1:!0,readonly:G?.readOnly??!1,strict:!0})}function j4($){$.exec(`
CREATE TABLE IF NOT EXISTS documents (
collection TEXT NOT NULL,
id TEXT NOT NULL,
json TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE VIRTUAL TABLE IF NOT EXISTS document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TABLE IF NOT EXISTS document_text_fts_keys (
rowid INTEGER PRIMARY KEY,
collection TEXT NOT NULL,
id TEXT NOT NULL,
UNIQUE (collection, id)
);
CREATE TABLE IF NOT EXISTS document_store_schema (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL
);
`);try{$.exec("BEGIN IMMEDIATE");let G=$.query("SELECT version FROM document_store_schema WHERE component = ?1");if(G.get(k$)?.version!==P$)$.exec(`
DROP TABLE document_text_fts;
CREATE VIRTUAL TABLE document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
DELETE FROM document_text_fts_keys;
INSERT INTO document_text_fts_keys (collection, id)
SELECT collection, id
FROM documents
WHERE CASE WHEN json_valid(json)
THEN json_type(json, '$.text') = 'text' OR
json_type(json, '$.searchText') = 'text'
ELSE 0
END;
INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
SELECT keys.rowid, documents.collection, documents.id,
CASE WHEN json_type(documents.json, '$.text') = 'text'
THEN json_extract(documents.json, '$.text')
END,
CASE WHEN json_type(documents.json, '$.searchText') = 'text'
THEN json_extract(documents.json, '$.searchText')
END
FROM documents
JOIN document_text_fts_keys AS keys
ON keys.collection = documents.collection AND keys.id = documents.id;
`),$.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(k$,P$);if(G.get(Q$)?.version!==E$)$.exec(`
DROP INDEX IF EXISTS documents_collection_scope_key_idx;
DROP INDEX IF EXISTS documents_collection_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_source_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_claim_group_idx;
CREATE INDEX documents_collection_scope_key_idx
ON documents (collection, json_extract(json, '$.scopeKey'))
WHERE json_valid(json);
CREATE INDEX documents_collection_memory_id_idx
ON documents (collection, json_extract(json, '$.memoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_source_memory_id_idx
ON documents (collection, json_extract(json, '$.sourceMemoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_claim_group_idx
ON documents (
collection,
json_extract(json, '$.scopeKey'),
json_extract(json, '$.subjectEntityId'),
json_extract(json, '$.predicateKey')
)
WHERE json_valid(json);
`),$.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(Q$,E$);$.exec("COMMIT")}catch(G){try{$.exec("ROLLBACK")}catch{}throw G}}function J4($){$.exec(`
CREATE TABLE IF NOT EXISTS session_buffers (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_working_memory (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_journals (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`)}function A4($){$.exec(`
CREATE TABLE IF NOT EXISTS vectors (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding_json TEXT NOT NULL,
metadata_json TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE TABLE IF NOT EXISTS vector_index_state (
table_name TEXT PRIMARY KEY,
collection TEXT NOT NULL,
dimension INTEGER NOT NULL,
dirty INTEGER NOT NULL
);
`)}function V($){return JSON.parse($)}function S($,G){let Y=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(G);return Y!==null&&Y!==void 0}function B4($,G,Y){let X=G.replaceAll('"','""');return $.query(`PRAGMA table_info("${X}")`).all().some(({name:H})=>H===Y)}function g($){return Error(`SQLite ${$} store is read-only in this context.`)}function O4($,G){let Y=Math.min($.length,G.length),X=0;for(let H=0;H<Y;H+=1)X+=$[H]*G[H];return X}function U4($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function z4($){switch($){case"memoryId":return"$.memoryId";case"predicateKey":return"$.predicateKey";case"scopeKey":return"$.scopeKey";case"sourceMemoryId":return"$.sourceMemoryId";case"subjectEntityId":return"$.subjectEntityId";default:return}}function a($,G){$.exec("BEGIN IMMEDIATE");try{let Y=G();return $.exec("COMMIT"),Y}catch(Y){try{$.exec("ROLLBACK")}catch{}throw Y}}function C$($){let{alias:G,keyParameterIndex:Y,value:X,valueParameterIndex:H}=$,F=`EXISTS (
SELECT 1
FROM json_each(metadata_json) AS ${G}
WHERE ${G}.key = ?${Y}`;if(X===null)return`${F}
AND ${G}.type = 'null'
)`;if(typeof X==="boolean")return`${F}
AND ${G}.type = '${X?"true":"false"}'
)`;if(typeof X==="number")return`${F}
AND ${G}.type IN ('integer', 'real')
AND ${G}.atom = ?${H}
)`;return`${F}
AND ${G}.type = 'text'
AND ${G}.atom = ?${H}
)`}function c($){return`"${$.replaceAll('"','""')}"`}function _4($){if(/^[A-Za-z0-9]+$/.test($))return $;return`x_${Y4.from($,"utf8").toString("hex")}`}function R$($,G){return`vss_vectors_${_4($)}_dim_${G}`}function n($,G,Y){$.query(`DELETE FROM ${c(G)} WHERE rowid = ?1`).run(Y)}function V$($){let{database:G,embeddingJson:Y,rowid:X,tableName:H}=$;n(G,H,X),G.query(`INSERT INTO ${c(H)} (rowid, embedding)
VALUES (?1, json(?2))`).run(X,Y)}function K4($){let{collection:G,config:Y,database:X,filter:H,queryEmbedding:F,topK:W}=$;if(Y.mode==="off"||!Y.paths?.length)return null;let B=[G,JSON.stringify(F)],M=[];if(H)for(let[U,q]of Object.entries(H)){if(!U4(q))return null;B.push(U);let N=B.length,T=`metadata_filter_${M.length+1}`;if(q===null||typeof q==="boolean"){M.push(C$({alias:T,keyParameterIndex:N,value:q}));continue}B.push(q),M.push(C$({alias:T,keyParameterIndex:N,value:q,valueParameterIndex:B.length}))}B.push(W);let E=["collection = ?1",...M];return X.query(`SELECT
id,
embedding_json,
metadata_json,
content,
${Y.searchFunction||G$}(embedding_json, ?2) AS score
FROM vectors
WHERE ${E.join(" AND ")}
ORDER BY score DESC, id ASC
LIMIT ?${B.length}`).all(...B).map((U)=>({id:U.id,embedding:V(U.embedding_json),metadata:V(U.metadata_json),content:U.content,score:Number(U.score)}))}function w4($,G){let Y=H$($,G);if(!G?.readOnly)j4(Y);let X=Y.query(`INSERT INTO documents (collection, id, json)
VALUES (?1, ?2, ?3)
ON CONFLICT(collection, id) DO UPDATE SET json = excluded.json`),H=Y.query("SELECT json FROM documents WHERE collection = ?1 AND id = ?2"),F=Y.query("SELECT json FROM documents WHERE collection = ?1"),W=Y.query("DELETE FROM documents WHERE collection = ?1 AND id = ?2"),B=S(Y,"document_text_fts"),M=S(Y,"document_text_fts_keys"),E=B&&B4(Y,"document_text_fts","searchText"),C=M?Y.query(`INSERT OR IGNORE INTO document_text_fts_keys (collection, id)
VALUES (?1, ?2)`):null,U=M?Y.query(`SELECT rowid FROM document_text_fts_keys
WHERE collection = ?1 AND id = ?2`):null,q=B?Y.query("DELETE FROM document_text_fts WHERE rowid = ?1"):null,N=B&&E?Y.query(`INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
VALUES (?1, ?2, ?3, ?4, ?5)`):null,T=M?Y.query("DELETE FROM document_text_fts_keys WHERE rowid = ?1"):null;function x(j,Z){let O=U?.get(j,Z);if(!O)return;q?.run(O.rowid),T?.run(O.rowid)}function d(j,Z,O){if(!q||!N||!C||!U)return;let z=U.get(j,Z);if(z)q.run(z.rowid);let R=X$(O,"searchText"),L=X$(O,"text");if(L===void 0&&R===void 0){if(z)T?.run(z.rowid);return}C.run(j,Z);let D=U.get(j,Z);N.run(D.rowid,j,Z,L??null,R??null)}function p(j){let Z=Object.entries(j.filter??{}),O=Z.length>0?[`json_valid(${j.alias}.json)`]:[];for(let[z,R]of Z){let L=z4(z);if(L){if(R===null){O.push(`json_type(${j.alias}.json, '${L}') = 'null'`);continue}j.values.push(R),O.push(`json_extract(${j.alias}.json, '${L}') = ?${j.values.length}`);continue}j.values.push(`$."${z.replaceAll('"',"\\\"")}"`);let D=j.values.length;if(R===null){O.push(`json_type(${j.alias}.json, ?${D}) = 'null'`);continue}j.values.push(R),O.push(`json_extract(${j.alias}.json, ?${D}) = ?${j.values.length}`)}return O}function l(j){Y.exec("BEGIN IMMEDIATE");try{for(let Z of[j.expected,...j.unchanged??[]]){let O=H.get(Z.collection,Z.id);if(!(Z.document===null?O===null:O!==null&&O.json===JSON.stringify(Z.document)))return Y.exec("ROLLBACK"),!1}for(let Z of j.set)X.run(Z.collection,Z.id,JSON.stringify(Z.document)),d(Z.collection,Z.id,Z.document);for(let Z of j.delete??[])W.run(Z.collection,Z.id),x(Z.collection,Z.id);return Y.exec("COMMIT"),!0}catch(Z){try{Y.exec("ROLLBACK")}catch{}throw Z}}return{projectionBatchSemantics:T$,async set(j,Z,O){a(Y,()=>{X.run(j,Z,JSON.stringify(O)),d(j,Z,O)})},async get(j,Z){let O=H.get(j,Z);return O?V(O.json):null},async update(j,Z,O){let z=await this.get(j,Z);if(!z)throw Error(`Document not found for update: ${j}/${Z}`);await this.set(j,Z,y$(z,O))},async query(j,Z){if(w$(Z),Z&&Object.keys(Z).length>0){let z=[j],R=p({alias:"documents",filter:Z,values:z});return Y.query(`SELECT json FROM documents
WHERE collection = ?1 AND ${R.join(" AND ")}`).all(...z).map((D)=>V(D.json))}return F.all(j).map((z)=>V(z.json))},async queryPage(j,Z){I$(Z);let O=[j],z=p({alias:"documents",filter:Z.filter,values:O});O.push(Z.cursor??null);let R=O.length;O.push(Z.limit+1);let L=Y.query(`SELECT documents.id, documents.json
FROM documents
WHERE documents.collection = ?1
${z.length>0?`AND ${z.join(" AND ")}`:""}
AND (?${R} IS NULL OR documents.id > ?${R})
ORDER BY documents.id ASC
LIMIT ?${O.length}`).all(...O),D=L.slice(0,Z.limit);return{items:D.map((y)=>V(y.json)),...L.length>Z.limit?{nextCursor:D.at(-1).id}:{}}},async searchText(j,Z){N$(Z);let O=S$(Z.query);if(O.length===0)return[];let z=[],R,L=Z.field==="text"?Z.field:Z.field==="searchText"&&E?Z.field:null;if(B&&L){z.push(O,j);let D=p({alias:"documents",filter:Z.filter,values:z});z.push(Z.limit),R=`SELECT documents.id, documents.json, bm25(document_text_fts) AS score
FROM document_text_fts
JOIN documents
ON documents.collection = document_text_fts.collection
AND documents.id = document_text_fts.id
WHERE document_text_fts.${L} MATCH ?1
AND document_text_fts.collection = ?2
${D.length>0?`AND ${D.join(" AND ")}`:""}
ORDER BY score ASC, documents.id ASC
LIMIT ?${z.length}`}else{z.push(j,`$."${Z.field.replaceAll('"',"\\\"")}"`);let D=f$(Z.query),y=[];for(let v of D)z.push(`%${v}%`),y.push(`lower(CAST(json_extract(documents.json, ?2) AS TEXT)) LIKE ?${z.length}`);let u=p({alias:"documents",filter:Z.filter,values:z});z.push(Z.limit),R=`SELECT documents.id, documents.json, 1 AS score
FROM documents
WHERE documents.collection = ?1
AND (${y.join(" OR ")})
${u.length>0?`AND ${u.join(" AND ")}`:""}
ORDER BY documents.id ASC
LIMIT ?${z.length}`}return Y.query(R).all(...z).map((D)=>({document:V(D.json),id:D.id,score:Math.max(Number.EPSILON,Math.abs(Number(D.score)))}))},async writeBatchIfUnchanged(j){if(G?.readOnly)throw g("document");return l(j)},async delete(j,Z){a(Y,()=>{x(j,Z),W.run(j,Z)})}}}function Z$($,G,Y){if(Y?.readOnly&&!S($,G))return{async set(){throw g("session")},async get(){return null},async setIfUnchanged(){throw g("session")},async deleteIfUnchanged(){throw g("session")},async deleteByScope(){throw g("session")}};let X=$.query(`INSERT INTO ${G} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO UPDATE SET json = excluded.json`),H=$.query(`SELECT json FROM ${G} WHERE scope_key = ?1`),F=$.query(`INSERT INTO ${G} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO NOTHING`),W=$.query(`UPDATE ${G}
SET json = ?3
WHERE scope_key = ?1 AND json = ?2`),B=$.query(`DELETE FROM ${G} WHERE scope_key = ?1`),M=$.query(`DELETE FROM ${G} WHERE scope_key = ?1 AND json = ?2`),E=$.query(`DELETE FROM ${G} WHERE scope_key LIKE ?1`);return{async set(C,U){X.run(b(C),JSON.stringify(U))},async setIfUnchanged(C,U,q){return a($,()=>{let N=b(C),T=JSON.stringify(q),x=U===null?F.run(N,T):W.run(N,JSON.stringify(U),T);return Number(x.changes??0)===1})},async get(C){let U=H.get(b(C));return U?V(U.json):null},async deleteIfUnchanged(C,U){return a($,()=>{let q=M.run(b(C),JSON.stringify(U));return Number(q.changes??0)===1})},async deleteByScope(C){if(C.sessionId!==void 0){let q=B.run(b(C));return Number(q.changes??0)}let U=E.run(`${L$(C)}%`);return Number(U.changes??0)}}}function y4($,G){let Y=H$($,G);if(!G?.readOnly)J4(Y);let X=Z$(Y,"session_buffers",G),H=Z$(Y,"session_working_memory",G),F=Z$(Y,"session_journals",G);return{saveBuffer(W,B){return X.set(W,B)},saveBufferIfUnchanged(W,B,M){return X.setIfUnchanged(W,B,M)},getBuffer(W){return X.get(W)},deleteBufferIfUnchanged(W,B){return X.deleteIfUnchanged(W,B)},deleteBuffersByScope(W){return X.deleteByScope(W)},saveWorkingMemory(W,B){return H.set(W,B)},getWorkingMemory(W){return H.get(W)},deleteWorkingMemoryByScope(W){return H.deleteByScope(W)},saveJournal(W,B){return F.set(W,B)},getJournal(W){return F.get(W)},deleteJournalsByScope(W){return F.deleteByScope(W)}}}function f4($,G,Y){let X=Y?.runtimeResolution??x$(),H=Y?.vectorExtensionConfig??X.config.vectorExtension,F=Y?.runtimeResolution?.diagnostics??X.diagnostics,W=H$($,G);if(!G?.readOnly)A4(W);if(F.requestedMode==="require"&&!F.available)throw Error(F.reason??"SQLite vector acceleration is required but no supported runtime is available.");let B=!G?.readOnly||S(W,"vectors"),M=new Set,E=null,C=G?.readOnly?null:W.query(`INSERT INTO vectors (
collection,
id,
embedding_json,
metadata_json,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(collection, id) DO UPDATE SET
embedding_json = excluded.embedding_json,
metadata_json = excluded.metadata_json,
content = excluded.content`),U=B?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,q=B?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,N=B?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,T=B?W.query(`SELECT rowid, embedding_json
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,x=B?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND rowid = ?2`):null,d=G?.readOnly?null:W.query("DELETE FROM vectors WHERE collection = ?1 AND id = ?2"),l=!G?.readOnly||S(W,"vector_index_state")?W.query(`SELECT dirty
FROM vector_index_state
WHERE table_name = ?1`):null,j=G?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 1)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 1`),Z=G?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 0)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 0`);function O(){if(E)return E;let J=(Y?.loadVectorExtension??D$)(H,W);return E=J&&typeof J==="object"&&"loaded"in J?J:{loaded:H.mode!=="off"&&Boolean(H.paths?.length)},E}function z(){return H.backend==="sqlite-vss"&&O().loaded}function R(J,K){let A=R$(J,K);j.run(A,J,K)}function L(J){Z.run(J.tableName,J.collection,J.dimension)}function D(J){if(!J.existed)return!0;let K=l.get(J.tableName);return!K||K.dirty!==0}function y(J){return l?.get(J)?.dirty===0}function u(J,K,A){let _=N.all(J).filter((P)=>{return V(P.embedding_json).length===K}),Q=new Set(_.map((P)=>P.rowid)),k=W.query(`SELECT rowid FROM ${c(A)}`).all();for(let P of k)if(!Q.has(P.rowid))n(W,A,P.rowid);for(let P of _)V$({database:W,embeddingJson:P.embedding_json,rowid:P.rowid,tableName:A});L({collection:J,dimension:K,tableName:A})}function v(J,K){if(!z())return null;let A=R$(J,K);if(M.has(A)){if(G?.readOnly){if(!y(A))return M.delete(A),null;return A}if(D({existed:!0,tableName:A}))u(J,K,A);return A}if(G?.readOnly){if(!S(W,A))return null;if(!y(A))return null;return M.add(A),A}let _=S(W,A);if(W.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${c(A)}
USING vss0(embedding(${K}))`),D({existed:_,tableName:A}))u(J,K,A);return M.add(A),A}function v$(J){let{collection:K,filter:A,queryEmbedding:_,topK:Q}=J,k=_.length,P=v(K,k);if(!P)return null;let I=q.all(K).filter((h)=>{return V(h.embedding_json).length===k}).length;if(I===0)return[];let s=JSON.stringify(_),w=Math.min(I,Math.max(Q,A?Q*4:Q));while(w>0){let h=W.query(`SELECT rowid, distance
FROM ${c(P)}
WHERE vss_search(embedding, vss_search_params(json(?1), ?2))`).all(s,w),f=[];for(let j$ of h){let r=x.get(K,j$.rowid);if(!r)continue;let h$=V(r.embedding_json),J$=V(r.metadata_json);if(!W$(J$,A))continue;f.push({id:r.id,embedding:h$,metadata:J$,content:r.content,score:1/(1+Number(j$.distance))})}if(!A||f.length>=Q||w>=I)return f.slice(0,Q);w=Math.min(I,w*2)}return[]}return{async upsert(J,K){if(G?.readOnly)throw g("vector");W.transaction((_)=>{let Q=z();for(let k of _){let P=T.get(J,k.id),I=P?V(P.embedding_json).length:null,s=JSON.stringify(k.embedding);if(C.run(J,k.id,s,JSON.stringify(k.metadata),k.content),!Q){if(P&&I!==null&&I!==k.embedding.length)R(J,I);R(J,k.embedding.length);continue}let w=T.get(J,k.id);if(!w)continue;if(P&&I!==null&&I!==k.embedding.length){let f=v(J,I);if(f)n(W,f,P.rowid)}let h=v(J,k.embedding.length);if(!h)continue;V$({database:W,embeddingJson:s,rowid:w.rowid,tableName:h})}})(K)},async get(J,K){if(!B)return null;let A=U.get(J,K);if(!A)return null;return{id:A.id,embedding:V(A.embedding_json),metadata:V(A.metadata_json),content:A.content}},async search(J,K,A){if(A.topK<=0||K.length===0)return[];if(!B)return[];if(H.mode!=="off"&&H.paths?.length&&O().loaded)try{let _=H.backend==="sqlite-vss"?v$({collection:J,filter:A.filter,queryEmbedding:K,topK:A.topK}):(Y?.runExtensionSearch??K4)({collection:J,config:H,database:W,filter:A.filter,queryEmbedding:K,topK:A.topK});if(_!==null)return _;if(H.mode==="require")throw Error("SQLite vector extension search could not satisfy the current query without durable fallback.")}catch(_){if(H.mode==="require"){let Q=_ instanceof Error?_.message:String(_);throw Error(`Failed to execute SQLite vector extension search for ${J}: ${Q}`)}}return q.all(J).map((_)=>{let Q=V(_.embedding_json),k=V(_.metadata_json);return{id:_.id,embedding:Q,metadata:k,content:_.content,score:O4(Q,K)}}).filter((_)=>W$(_.metadata,A.filter)).sort((_,Q)=>{if(Q.score!==_.score)return Q.score-_.score;return _.id.localeCompare(Q.id)}).slice(0,A.topK)},async delete(J,K){if(G?.readOnly)throw g("vector");W.transaction(()=>{let _=T.get(J,K),Q=z();if(_&&Q){let k=V(_.embedding_json).length,P=v(J,k);if(P)n(W,P,_.rowid)}if(_&&!Q){let k=V(_.embedding_json).length;R(J,k)}d.run(J,K)})()}}}export{f4 as createSQLiteVectorStore,y4 as createSQLiteSessionStore,w4 as createSQLiteDocumentStore};
import{Zb as V}from"./chunk-081j36ca.js";import{_b as U}from"./chunk-n9j0rb5c.js";import{ac as R}from"./chunk-eqpe4gcb.js";var E=R((M,Q)=>{var{defineProperty:K,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(q,v)=>{for(var z in v)K(q,z,{get:v[z],enumerable:!0})},$=(q,v,z,F)=>{if(v&&typeof v==="object"||typeof v==="function"){for(let G of X(v))if(!Y.call(q,G)&&G!==z)K(q,G,{get:()=>v[G],enumerable:!(F=W(v,G))||F.enumerable})}return q},A=(q)=>$(K({},"__esModule",{value:!0}),q),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var H=U(),B=V();async function D(){let{projectId:q,teamId:v}=(0,B.findProjectInfo)(),z=(0,B.loadToken)(q);if(!z||(0,B.isExpired)((0,B.getTokenPayload)(z.token))){let F=await(0,B.getVercelCliToken)();if(!F)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!q)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(z=await(0,B.getVercelOidcToken)(F,q,v),!z)throw new H.VercelOidcTokenError("Failed to refresh OIDC token");(0,B.saveToken)(z,q)}process.env.VERCEL_OIDC_TOKEN=z.token;return}});export default E();
import{Ma as Or,Ta as br,Xa as Qr,_a as Kr,cb as Sr,db as dr,kb as qr,ob as sr,sb as jr,wb as C,yb as g}from"./chunk-0h5pry7v.js";import{Ib as hr}from"./chunk-jr0h5wkn.js";class M extends Error{diagnostics;constructor(r,s){super(r);this.diagnostics=s;this.name="HostAdapterWriteError"}}function L(r){return typeof r==="object"&&r!==null}function yr(r){if(!L(r))return!1;let s=Object.getPrototypeOf(r);return s===null||s===Object.prototype}function V(r,s){if(typeof r!=="string"||r.trim().length===0)throw Error(`${s} must be a non-empty string`);return r.trim()}function y(r,s){if(r===void 0)return;return V(r,s)}function e(r,s){if(r===null||typeof r==="boolean"||typeof r==="number"||typeof r==="string"){if(typeof r==="number"&&!Number.isFinite(r))throw Error(`${s} must be a JSON-serializable value`);return r}if(Array.isArray(r))return r.map((o,H)=>e(o,`${s}[${H}]`));if(yr(r)){let o={};for(let[H,f]of Object.entries(r)){if(f===void 0)throw Error(`${s}.${H} must not be undefined`);o[H]=e(f,`${s}.${H}`)}return o}throw Error(`${s} must be a JSON-serializable value`)}function Lr(r,s){if(typeof r!=="number"||!Number.isInteger(r)||r<0)throw Error(`${s} must be a non-negative integer`);return r}function kr(r,s){let o=V(r,s);if(Number.isNaN(Date.parse(o)))throw Error(`${s} must be a valid date-time string`);return o}function cr(r,s){if(r==="generic"||r==="claude"||r==="codex")return r;throw Error(`${s} must be generic, claude, or codex`)}function Cr(r,s){if(!L(r))throw Error(`${s} must be an object`);return{userId:V(r.userId,`${s}.userId`),...r.tenantId!==void 0?{tenantId:V(r.tenantId,`${s}.tenantId`)}:{},...r.workspaceId!==void 0?{workspaceId:V(r.workspaceId,`${s}.workspaceId`)}:{},...r.agentId!==void 0?{agentId:V(r.agentId,`${s}.agentId`)}:{},...r.sessionId!==void 0?{sessionId:V(r.sessionId,`${s}.sessionId`)}:{}}}function xr(r,s){let o=V(r,s),H=o.split("/");if(o.startsWith("/")||o.startsWith("~/")||o.includes("\\")||/^[A-Za-z]:[\\/]/.test(o))throw Error(`${s} must be a normalized relative path without traversal or absolute segments`);if(H.some((f)=>f.length===0||f==="."||f===".."))throw Error(`${s} must be a normalized relative path without traversal or absolute segments`);return o}function gr(r,s){return{kind:"command",command:V(r.command,`${s}.command`),...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function lr(r,s){let o=r.payload===void 0?void 0:e(r.payload,`${s}.payload`);return{kind:"tool_call",toolName:V(r.toolName,`${s}.toolName`),...o!==void 0?{payload:o}:{},...r.raw!==void 0?{raw:y(r.raw,`${s}.raw`)}:{},...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function er(r,s){if(r.operation!=="create"&&r.operation!=="delete"&&r.operation!=="update")throw Error(`${s}.operation must be create, delete, or update`);return{kind:"file_edit",operation:r.operation,relativePath:xr(r.relativePath,`${s}.relativePath`),...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function tr(r,s){if(!L(r))throw Error(`${s} must be an object`);if(r.kind==="command")return gr(r,s);if(r.kind==="tool_call")return lr(r,s);if(r.kind==="file_edit")return er(r,s);throw Error(`${s}.kind must be command, tool_call, or file_edit`)}function t(r,s="actionIntent"){if(!L(r))throw Error(`${s} must be an object`);let o=r.runId===void 0?void 0:V(r.runId,`${s}.runId`),H=r.attemptId===void 0?void 0:V(r.attemptId,`${s}.attemptId`);if(!o&&!H)throw Error(`${s} must include runId or attemptId`);let f={actionId:V(r.actionId,`${s}.actionId`),hostKind:cr(r.hostKind,`${s}.hostKind`),occurredAt:kr(r.occurredAt,`${s}.occurredAt`),scope:Cr(r.scope,`${s}.scope`),sequence:Lr(r.sequence,`${s}.sequence`),turnId:V(r.turnId,`${s}.turnId`),action:tr(r.action,`${s}.action`)};if(o)return{...f,runId:o,...H?{attemptId:H}:{}};return{...f,attemptId:H}}function wo(r){try{return t(r),!0}catch{return!1}}function fr(r){return typeof r==="object"&&r!==null}function k(r,s){if(typeof r!=="string"||r.trim().length===0)throw Error(`${s} must be a non-empty string`);return r}function Hr(r,s){if(typeof r!=="number"||!Number.isInteger(r)||r<0)throw Error(`${s} must be a non-negative integer`);return r}function nr(r,s){if(r==="command"||r==="tool_call"||r==="warning")return r;throw Error(`${s} must be command, tool_call, or warning`)}function ar(r,s){if(r==="failure"||r==="success"||r==="timeout"||r==="user_corrected")return r;throw Error(`${s} must be failure, success, timeout, or user_corrected`)}function ir(r,s){if(r==="host_lifecycle"||r==="warning_message")return r;throw Error(`${s} must be host_lifecycle or warning_message`)}function n(r,s="trace.events[0]"){if(!fr(r))throw Error(`${s} must be an object`);let o=r.args;if(o!==void 0&&(!Array.isArray(o)||o.some((A)=>typeof A!=="string")))throw Error(`${s}.args must be a string array`);let H=r.raw;if(H!==void 0&&typeof H!=="string")throw Error(`${s}.raw must be a string`);let f=r.evidenceExcerpt;if(f!==void 0&&typeof f!=="string")throw Error(`${s}.evidenceExcerpt must be a string`);let E=r.correctionOfStepIndex===void 0?void 0:Hr(r.correctionOfStepIndex,`${s}.correctionOfStepIndex`),w=Hr(r.stepIndex,`${s}.stepIndex`),m=r.outcomeSource===void 0?void 0:ir(r.outcomeSource,`${s}.outcomeSource`),$=r.turnId;if($!==void 0&&typeof $!=="string")throw Error(`${s}.turnId must be a string`);return{actionKind:nr(r.actionKind,`${s}.actionKind`),actionName:k(r.actionName,`${s}.actionName`),...o?{args:[...o]}:{},...typeof E==="number"?{correctionOfStepIndex:E}:{},...typeof f==="string"?{evidenceExcerpt:f}:{},outcome:ar(r.outcome,`${s}.outcome`),...typeof m==="string"?{outcomeSource:m}:{},...typeof H==="string"&&H.trim().length>0?{raw:H}:{},stepIndex:w,...typeof $==="string"&&$.trim().length>0?{turnId:$}:{}}}function Er(r,s="trace"){if(!fr(r))throw Error(`${s} must be an object`);let o=k(r.hostKind,`${s}.hostKind`);if(o!=="codex")throw Error(`${s}.hostKind must be codex`);let H=r.events;if(!Array.isArray(H)||H.length===0)throw Error(`${s}.events must be a non-empty array`);let f=H.map((w,m)=>n(w,`${s}.events[${m}]`)),E=new Map;for(let[w,m]of f.entries()){let $=E.get(m.stepIndex);if($!==void 0)throw Error(`${s}.events[${w}].stepIndex duplicates ${s}.events[${$}].stepIndex`);E.set(m.stepIndex,w)}return{cue:k(r.cue,`${s}.cue`),hostKind:o,traceId:k(r.traceId,`${s}.traceId`),events:f}}function wr(r){let s;for(let o of r.events)if(!s||o.stepIndex<s.stepIndex)s=o;return s}function a(r){return{kind:r.actionKind,name:r.actionName,...r.args?{args:[...r.args]}:{},...r.raw?{raw:r.raw}:{}}}function Ar(r){if(r.events.length===0)return null;return Er({cue:r.cue,hostKind:r.hostKind,traceId:r.traceId,events:r.events},"trace")}function mr(r,s){return r instanceof Error?r:Error(s)}function $r(r){let s=[],o=null,H=0;return{appendEvent(f){if(o)throw Error("behavioral trace recorder is already closed");let E=n({...f,stepIndex:H},"trace.events[0]");return s.push(E),H+=1,E},close(){if(o)return o;return o=(async()=>{let f=null;try{f=Ar({...r,events:s})}catch(E){return{error:mr(E,"failed to build behavioral trace"),recorded:!1,trace:null}}if(!f)return{recorded:!1,trace:null};try{return{recorded:(await r.onClose?.(f))?.recorded??!1,trace:f}}catch(E){return{error:mr(E,"failed to record behavioral trace"),recorded:!1,trace:f}}})(),o},snapshot(){return Ar({...r,events:s})}}}var ur=Symbol.for("goodmemory.host.eval.support");function Br(r,s){return r[ur]=s,r}var z="host_pre_action_policy",pr=["deepanalyzer","deploy","drop","git push","migration","prod","production","publish","release","rm -"],rs=["agents.md","claude.md","package.json","playbooks/","src/","task-board/"],ss={correction_context:4,verification_result:3,tool_result_excerpt:2,document_excerpt:2,conversation_excerpt:1},os=new Set(["&&",";","|","||"]),Hs=new Set(["command","env","exec","nohup"]),Ir=/^[A-Za-z_][A-Za-z0-9_]*=/u;function Q(r){let s=new Set,o=[];for(let H of r){if(!H)continue;let f=H.trim();if(f.length===0||s.has(f))continue;s.add(f),o.push(f)}return o}function q(r){return r?.trim().toLowerCase()??""}function c(r,s,o,H){if(o.length===0||H.length===0)return 0;return r.tokenOverlap(o,H,s,{excludeStopwords:!0})}function D(r,s,o){return r.resolveFromText({...o?{locale:o}:{},text:s})}function Z(r,s,o,H){let f=r.render({key:o},s);return H?`${f}: ${H}`:f}function i(r){switch(r.kind){case"command":return[r.command,r.summary].filter(Boolean).join(" ");case"tool_call":return[r.toolName,r.raw,r.summary,r.payload?JSON.stringify(r.payload):void 0].filter(Boolean).join(" ");case"file_edit":return[r.operation,r.relativePath,r.summary].filter(Boolean).join(" ")}}function u(r){return i(r)}function fs(r){return r.kind==="validated_pattern"&&r.lifecycle==="active"&&!r.supersededBy}function Es(r){let s=Or(r.appliesTo);return s==="coding_agent"||s==="general_response"}function ws(r,s){let o=r.durable.evidence.filter((E)=>E.linkedMemoryIds.includes(s)).map((E)=>E.id),H=r.durable.experiences.filter((E)=>E.linkedMemoryIds.includes(s)).flatMap((E)=>E.linkedEvidenceIds),f=r.durable.promotions.filter((E)=>E.linkedMemoryIds.includes(s)).flatMap((E)=>E.linkedEvidenceIds);return Q([...As(r,s),...o,...H,...f])}function As(r,s){let o=r.durable.feedback.find((H)=>H.id===s);return Q(o?.evidence??[])}function ms(r,s,o){return s.splitClauses(r,o).map((H)=>H.trim()).filter((H)=>H.length>0)}function $s(r){let s=Wr(r.action).map((E)=>r.language.normalizeForEquality(E.split(/[\\/]/u).at(-1)??E,r.languageContext)),o=!1,H=!1,f=!1;for(let E of ms(r.rule,r.language,r.languageContext)){let w=Vr({languageContext:r.languageContext,text:E},r.language);o||=w;let m=r.language.buildSearchTerms(E,r.languageContext);if(!(s.some((R)=>m.includes(R))||c(r.language,r.languageContext,E,r.actionText)>0))continue;if(w)H=!0;else f=!0}if(H)return"matched";if(o&&f)return"allowed_replacement";return f?"matched":"none"}function Bs(r,s,o,H){return r.durable.feedback.filter((f)=>fs(f)&&Es(f)).map((f)=>{let E=[f.rule,f.why].filter(Boolean).join(" "),w=D(H,E,f.source.locale),m=c(H,w,E,o),$=H.normalizeForEquality(E,w),A=H.normalizeForEquality(u(s.action),w),R=H.normalizeForEquality(o,w),B=$s({action:s.action,actionText:o,language:H,languageContext:w,rule:E});if(!(B!=="allowed_replacement"&&(B==="matched"||m>0||$.includes(A)||$.includes(R))))return null;return{languageContext:w,pattern:f,linkedEvidenceIds:ws(r,f.id),score:m+(f.why?1:0)+Math.round(f.confidence)}}).filter((f)=>Boolean(f)).sort((f,E)=>E.score-f.score)}function Is(r,s,o){return r.durable.evidence.map((H)=>{let f=D(o,H.excerpt,H.source.locale),E=c(o,f,H.excerpt,s);if(E===0)return null;return{evidence:H,languageContext:f,score:E+ss[H.kind]}}).filter((H)=>Boolean(H)).sort((H,f)=>f.score-H.score)}function Nr(r){if(r.kind==="file_edit"){if(r.operation==="delete")return!0;let o=q(r.relativePath);return rs.some((H)=>o.includes(H))}let s=q(i(r));return pr.some((o)=>s.includes(o))}function Vr(r,s){let o=s.analyzeContent(r.text,r.languageContext);return o.feedbackKind==="dont"||o.factPolarity==="negative"}function Rs(r,s){let o=Sr({appliesTo:"coding_agent",kind:"do",language:s,languageContext:r.languageContext,rule:r.text}),H=o.enactmentSurface==="host_action"?o.applicability.canonicalFirstAction:void 0;return q(H?.name)==="quickcheck"?r.text:void 0}function _s(r,s){let o=[];for(let H of r){let f=s.splitSentences(H.text,H.languageContext).find((w)=>s.analyzeQuery(w,H.languageContext).before);if(f){o.push(f);continue}let E=Rs(H,s);if(E)o.push(E)}return Q(o)}function Os(r){return[...r.matchAll(/'([^']*)'|"([^"]*)"|(&&|\|\||[;|])|([^\s;&|]+)/gu)].map((s)=>s[1]??s[2]??s[3]??s[4]??"").filter((s)=>s.length>0)}function Rr(r){let s=0;while(Ir.test(r[s]??""))s+=1;while(s<r.length){let o=r[s],H=q(o.split(/[\\/]/u).at(-1));if(!Hs.has(H))return o;s+=1;while((r[s]??"").startsWith("-"))s+=1;while(Ir.test(r[s]??""))s+=1;if(s>=r.length)return o}return}function Wr(r){let o=(r.kind==="command"?r.command:r.kind==="tool_call"?r.raw:void 0)?.trim();if(!o)return[];let H=[],f=[];for(let w of Os(o)){if(os.has(w)){let m=Rr(f);if(m)H.push(m);f=[];continue}f.push(w)}let E=Rr(f);if(E)H.push(E);return Q(H)}function Ks(r){return Wr(r)[0]}function Ss(r,s){let o=r?.trim();if(!o||!o.includes("/"))return;let H=o.lastIndexOf("/");if(H<0)return;return`${o.slice(0,H+1)}${s}`}function ds(r,s,o,H){let f=r[0];if(!f)return;if(q(f).includes("quickcheck")){let w=Ss(Ks(s),"QuickCheck");if(w)return{kind:"tool_call",toolName:"QuickCheck",raw:w,summary:Z(o,H,"instruction",f)};return{kind:"warning",message:f}}return{kind:"warning",message:f}}function _r(r){return[...r.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/gu)].map((s)=>s[1]??s[2]??s[3]??"").filter((s)=>s.length>0)}function Pr(r){if(r.kind==="tool_call"){let s=r.raw?.trim();return{...s?{args:_r(s).slice(1),raw:s}:{},kind:"tool_call",name:r.toolName}}if(r.kind==="command"){let s=r.command.trim(),o=_r(s);return{args:o.slice(1),kind:"command",name:o[0]??s,raw:s}}return{kind:"warning",name:"file_edit",raw:`${r.operation} ${r.relativePath}`}}function Ns(r,s,o,H){if(r.kind==="warning")return{kind:"warning",message:r.raw??r.name};if(r.kind==="tool_call")return{kind:"tool_call",toolName:r.name,...r.raw?{raw:r.raw}:{},summary:Z(o,H,"instruction",s)};return{command:r.raw??[r.name,...r.args??[]].filter(Boolean).join(" "),kind:"command",summary:Z(o,H,"instruction",s)}}function Vs(r,s,o,H){let f=dr({appliesTo:"coding_agent",feedback:r.durable.feedback,query:o,surface:"host_action"}),E=Pr(s.action);return f.map((w)=>{let m=[w.feedback.rule,w.feedback.why].filter(Boolean).join(" "),$=D(H,m,w.feedback.source.locale),A=c(H,$,m,o),R=w.policy.applicability.canonicalFirstAction,B=R&&q(R.name)===q(E.name);if(w.matchedQueryTokens.length===0&&A===0&&!B)return null;return{feedback:w.feedback,languageContext:$,policy:w.policy,score:w.score+A}}).filter((w)=>Boolean(w)).sort((w,m)=>m.score-w.score)}function Ws(r){let s=[],o=Nr(r.action);if(r.workingMemory?.temporaryDecisions?.length)s.push(...r.workingMemory.temporaryDecisions);if(o&&r.workingMemory?.openLoops?.length){let H=r.workingMemory.openLoops[0],f=D(r.language,H);s.push(Z(r.language,f,"guidance",H))}if(o&&r.journal?.workflow?.length){let H=r.journal.workflow[0],f=D(r.language,H);s.push(`${r.language.render({key:"workflow"},f)}: ${H}`)}if(r.journal?.errorsAndCorrections?.length)s.push(r.journal.errorsAndCorrections[0]);return Q(s)}function Ps(r){return Q([z,`${z}.decision=${r.decision}`,`${z}.action_kind=${r.intent.action.kind}`,`${z}.host_kind=${r.intent.hostKind}`,r.highRisk?`${z}.high_risk`:void 0,r.matchedMemoryIds.length>0?`${z}.matched_memory=${r.matchedMemoryIds.length}`:void 0,r.matchedEvidenceIds.length>0?`${z}.matched_evidence=${r.matchedEvidenceIds.length}`:void 0])}function Fs(r){if(r.kind==="file_edit")return r.operation==="delete";if(r.kind==="command"){let s=q(r.command);return s.includes("rm -")||s.includes("git reset --hard")}return!1}function Fr(r){let s=i(r.intent.action),o=Vs(r.exported,r.intent,s,r.language),H=Bs(r.exported,r.intent,s,r.language),f=Is(r.exported,s,r.language),E=Q([...o.map((_)=>_.feedback.id),...H.map((_)=>_.pattern.id)]),w=Q([...o.flatMap((_)=>_.feedback.evidence??[]),...H.flatMap((_)=>_.linkedEvidenceIds),...f.map((_)=>_.evidence.id)]),m=H.flatMap((_)=>[_.pattern.rule,_.pattern.why].filter((h)=>Boolean(h)).map((h)=>({languageContext:_.languageContext,text:h}))),$=f.map((_)=>({languageContext:_.languageContext,text:_.evidence.excerpt})),A=[...m,...$],R=_s(A,r.language),B=Ws({action:r.intent.action,journal:r.exported.runtime?.journal,language:r.language,workingMemory:r.exported.runtime?.workingMemory}),W=Q([...m.map(({text:_})=>_),...B]).slice(0,4),K=Nr(r.intent.action),O=E.length>0||w.length>0,P=A.some((_)=>Vr(_,r.language)),S=o[0],Y=S?{languageContext:S.languageContext,text:S.feedback.rule}:A[0],J=D(r.language,s),G=Y?.languageContext??J,F="allow",b=Z(r.language,J,"guidance",Z(r.language,J,"none")),U,l=Pr(r.intent.action),j=S?.policy.applicability.canonicalFirstAction;if(S&&j){if(W.unshift(S.feedback.rule),!Kr(l,j))F="review_required",b=Z(r.language,S.languageContext,"instruction",S.feedback.rule),U=Ns(j,S.feedback.rule,r.language,S.languageContext);else if(W.length>0)F="allow_with_guidance",b=Z(r.language,S.languageContext,"verification",S.feedback.rule)}if(F==="allow"&&O&&K&&(P||R.length>0))if(U=ds(R,r.intent.action,r.language,G),Fs(r.intent.action)&&!U)F="blocked",b=Z(r.language,G,"instruction",Y?.text);else F="review_required",b=Z(r.language,G,"instruction",Y?.text),U??={kind:"warning",message:Y?.text??b};else if(F==="allow"&&W.length>0){F="allow_with_guidance";let _=D(r.language,W[0]);b=Z(r.language,_,"guidance",W[0])}let I=Ps({decision:F,highRisk:K,intent:r.intent,matchedEvidenceIds:w,matchedMemoryIds:E});return{actionId:r.intent.actionId,auditRecorded:!1,decision:F,guidance:W,matchedEvidenceIds:w,matchedMemoryIds:E,policyApplied:I,reason:b,...U?{recommendedFirstStep:U}:{},requiredPreconditions:R}}function Js(r){if(r==="timeout")return"timeout";if(r==="user_corrected")return"user correction";return"failure"}function Us(r){return r==="failure"||r==="timeout"||r==="user_corrected"}function Jr(r){return r.outcome==="success"||r.actionKind==="warning"}function Ys(r){let s=[...r.trace.events].filter((E)=>E.stepIndex>r.firstAction.stepIndex).sort((E,w)=>E.stepIndex-w.stepIndex),o=s.find((E)=>E.correctionOfStepIndex===r.firstAction.stepIndex&&Jr(E)),H=s.find((E)=>Jr(E)),f=o??H;return f?a(f):void 0}function Zs(r){let s=wr(r);if(!s||!Us(s.outcome))return null;return{cue:r.cue,evidenceExcerpt:s.evidenceExcerpt,failureClass:Js(s.outcome),firstAction:a(s),retrievalProfile:"coding_agent",saferAlternative:Ys({firstAction:s,trace:r})}}async function p(r){let s=C(r.memory),o=Zs(r.trace);if(!s?.recordBehavioralOutcome||!o)return{...o?{outcome:o}:{},recorded:!1};return await s.recordBehavioralOutcome({scope:r.scope,cue:o.cue,evidenceExcerpt:o.evidenceExcerpt,failureClass:o.failureClass,firstAction:o.firstAction,saferAlternative:o.saferAlternative,modelInfluence:o.modelInfluence,outcome:o.outcome}),{outcome:o,recorded:!0}}var zr=["memory_index","user_memory","session_memory"],Dr=[...zr,"archive_recap","playbook"];function d(r){return r.trim().replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\t/g,"\\t").replace(/\r\n?/g,`
`).replace(/\n/g,"\\n")}function Gs(r,s,o="none"){return[`## ${d(r)}`,...s.length>0?s:[`- ${d(o)}`]].join(`
`)}function Xs(r,s){return[`# ${d(r)}`,...s.flatMap((o)=>["",o])].join(`
`)}function v(r,s,o,H){return r.render({key:o,...H?{values:H}:{}},s)}function X(r,s,o,H){return Gs(v(r,s,o),H,v(r,s,"none"))}function rr(r,s){let o=r??s,H=[];for(let f of o)if(!H.includes(f))H.push(f);return H}function Ur(r){return Object.freeze([...r])}function bs(r){if(r.kind==="archive"||r.relativePath.startsWith("archive/"))return"archive_recap";if(r.relativePath.startsWith("playbooks/"))return"playbook";if(r.relativePath==="MEMORY.md"||r.kind==="memory")return"memory_index";if(r.relativePath==="user.md"||r.kind==="user")return"user_memory";if(r.kind==="session"||r.relativePath==="session.md")return"session_memory";return null}function hs(r){let s=r.readableArtifactTypes.filter((o)=>!r.supportedReadableArtifactTypes.includes(o));if(s.length===0)return;throw Error(`readable artifact types must be supported by the configured export surface: ${s.join(", ")}`)}function Qs(r){if(r.mode!=="file-authoritative"&&r.writableArtifactTypes.length>0)throw Error("file-assisted adapters cannot declare writable artifact types");if(r.writableArtifactTypes.length>0&&!r.documentStorePresent)throw Error("file-authoritative adapters require documentStore when writable artifact types are enabled");for(let s of r.writableArtifactTypes)if(!r.readableArtifactTypes.includes(s))throw Error("writable artifact types must be a subset of readable artifact types")}function qs(r){return Boolean(C(r)?.recordBehavioralOutcome)}function js(r){return Boolean(g(r)?.recordHostActionAssessment)}function zs(r){if(!r)return;switch(r.kind){case"warning":return r.message;case"command":return r.command;case"tool_call":return r.toolName;case"file_edit":return`${r.operation} ${r.relativePath}`}}function Ds(r,s){if(r.hostKind!==s)throw Error(`host action intent hostKind ${r.hostKind} does not match adapter hostKind ${s}`);return{...r,hostKind:s}}async function Ts(r){if(!js(r.memory))return{auditRecorded:!1};let s=await g(r.memory).recordHostActionAssessment({assessment:{actionId:r.intent.actionId,actionKind:r.intent.action.kind,actionSummary:u(r.intent.action),attemptId:r.intent.attemptId,decision:r.assessment.decision,guidance:r.assessment.guidance,hostKind:r.intent.hostKind,matchedEvidenceIds:r.assessment.matchedEvidenceIds,matchedMemoryIds:r.assessment.matchedMemoryIds,occurredAt:r.intent.occurredAt,policyApplied:r.assessment.policyApplied,reason:r.assessment.reason,recommendedFirstStepSummary:zs(r.assessment.recommendedFirstStep),requiredPreconditions:r.assessment.requiredPreconditions,runId:r.intent.runId,scope:r.intent.scope,turnId:r.intent.turnId}});return{assessmentExperienceId:s.experienceId,auditRecorded:s.recorded}}function vs(r,s){return[`- userId: ${d(r.scope.userId)}`,r.scope.workspaceId?`- workspaceId: ${d(r.scope.workspaceId)}`:void 0,r.scope.agentId?`- agentId: ${d(r.scope.agentId)}`:void 0,`- sessionId: ${d(s)}`].filter((o)=>Boolean(o))}function Ms(r){if(!r)return{constraints:[],currentGoal:[],openLoops:[],recentDecisions:[]};return{currentGoal:r.currentGoal?[`- ${d(r.currentGoal)}`]:[],openLoops:r.openLoops.map((s)=>`- ${d(s)}`),recentDecisions:(r.temporaryDecisions??[]).map((s)=>`- ${d(s)}`),constraints:(r.constraints??[]).map((s)=>`- ${d(s)}`)}}function ys(r){if(!r)return{currentState:[],keyFiles:[],workflow:[]};return{currentState:r.currentState?[`- ${d(r.currentState)}`]:[],keyFiles:(r.filesAndFunctions??[]).map((s)=>`- ${d(s)}`),workflow:(r.workflow??[]).map((s)=>`- ${d(s)}`)}}function Ls(r){return r.map((s)=>{let o=d(s.title),H=d(s.pointer);return`- ${o}: ${H}`})}function ks(r){return r.map((s)=>`- [${s.kind}] ${d(s.rule)}`)}function cs(r){return r.map((s)=>`- ${d(s.preview)}`)}function Cs(r){let s=new Set,o=[];for(let H of r){if(s.has(H))continue;s.add(H),o.push(H)}return o}function Yr(r){return(r.lifecycle??"active")==="active"}function xs(r){return`session-memory/${encodeURIComponent(r)}.md`}function gs(r,s,o,H){let f=r.runtime?.workingMemory?.sessionId===s?r.runtime.workingMemory:null,E=r.runtime?.journal?.sessionId===s?r.runtime.journal:null,w=r.durable.references.filter((B)=>B.sessionId===s&&Yr(B)),m=r.durable.feedback.filter((B)=>B.sessionId===s&&Yr(B)),$=(r.runtime?.spills??[]).filter((B)=>B.scope.sessionId===s),A=Ms(f),R=ys(E);return Xs(v(o,H,"session_handoff",{sessionId:s}),[X(o,H,"scope",vs(r,s)),X(o,H,"current_goal",A.currentGoal),X(o,H,"open_loops",A.openLoops),X(o,H,"recent_decisions",A.recentDecisions),X(o,H,"constraints",A.constraints),X(o,H,"current_state",R.currentState),X(o,H,"key_files",Cs([...R.keyFiles,...Ls(w)])),X(o,H,"workflow",R.workflow),X(o,H,"procedural_memory",ks(m)),X(o,H,"artifact_spills",cs($))])}function ls(r,s,o,H,f){if(o==="session_memory"&&s.sessionId)return{...s,artifactType:o,relativePath:xs(s.sessionId),content:gs(r,s.sessionId,H,f),writable:!1};return{...s,artifactType:o,writable:!1}}function es(r){let s=r.durable.profile,o=r.runtime?.workingMemory,H=r.runtime?.journal;return[...(r.durable.sourceMessages??[]).map(({content:f})=>f),s?.identity.name,s?.identity.role,s?.identity.organization,s?.identity.location,s?.identity.languagePreference,...r.durable.facts.map(({content:f})=>f),...r.durable.references.flatMap(({pointer:f,title:E})=>[E,f]),...r.durable.feedback.map(({rule:f})=>f),...r.durable.episodes.map(({summary:f})=>f),...r.durable.archives.map(({summary:f})=>f),...r.durable.evidence.map(({excerpt:f})=>f),...r.durable.experiences.map(({summary:f})=>f),...r.durable.proposals.map(({summary:f})=>f),...r.durable.promotions.map(({summary:f})=>f),o?.currentGoal,...o?.openLoops??[],...o?.temporaryDecisions??[],...o?.constraints??[],H?.currentState,...H?.worklog??[],...H?.filesAndFunctions??[],...H?.workflow??[]].filter((f)=>Boolean(f)).join(`
`)}async function Tr(r,s,o,H){let f=await r.exportMemory(o),E=H.resolveFromText({...o.locale?{locale:o.locale}:{},text:es(f)});return{artifacts:f.artifacts.files.flatMap((m)=>{let $=bs(m);if(!$||!s.includes($))return[];return[ls(f,m,$,H,E)]}),exportedAt:f.exportedAt,rootPath:f.artifacts.rootPath,scope:f.scope}}function ts(r=!1){return{mode:"file-assisted",hint:"Recreate the host adapter in file-assisted mode and inspect compiled artifacts before retrying writable operations.",performed:r}}function T(r){return{adapterId:r.adapterId,artifactType:r.artifactType,canonicalMemoryId:r.canonicalMemoryId,failureReasons:r.failureReasons??[],hostKind:r.hostKind,mode:r.mode,policyApplied:r.policyApplied??[],provenance:{adapterId:r.adapterId,hostKind:r.hostKind,origin:"host_adapter",wroteAt:r.wroteAt},relativePath:r.relativePath,risky:r.risky??!1,rollback:ts(r.rollbackPerformed??!1),structuredDelta:r.structuredDelta??[],verificationOutcome:r.verificationOutcome??"not_run"}}function N(r,s){return new M(r,s)}function x(r){return r.map((s)=>s.trim()).filter((s)=>s.startsWith("- ")).map((s)=>s.slice(2).trim())}function vr(r){let s=x(r),o={};for(let H of s){let f=H.indexOf(":");if(f<0)continue;let E=H.slice(0,f).trim(),w=H.slice(f+1).trim();o[E]=w}return o}function or(r){let s=new Map,o=null;for(let H of r.split(/\r?\n/)){let f=H.trimEnd();if(f.startsWith("## ")){o=f.slice(3).trim(),s.set(o,[]);continue}if(o)s.get(o)?.push(f)}return s}function Zr(r,s){let o=or(r);return x(o.get(s)??[])}function Gr(r){return r.length===1&&r[0]==="none"}function ns(r,s){return{canonicalPattern:v(r,s,"canonical_pattern"),guidance:v(r,s,"guidance"),why:v(r,s,"why")}}function as(r,s){let o=or(r.content),H=vr(o.get(s.canonicalPattern)??[]),f=x(o.get(s.guidance)??[]),E=x(o.get(s.why)??[]);if(!H.canonicalMemoryId)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback requires canonicalMemoryId in the Canonical Pattern section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(f.length===0)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback requires one guidance bullet in the Guidance section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(f.length>1)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback only supports a single guidance bullet in the Guidance section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(E.length>1)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback only supports zero or one Why bullet in the Why section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));return{appliesTo:H.appliesTo,canonicalMemoryId:H.canonicalMemoryId,rule:f[0],why:E[0]}}function is(r,s){let o=or(r),f=vr(o.get(s.canonicalPattern)??[]).canonicalMemoryId?.trim();return f?f:null}function us(r){return{id:"host-write-candidate",kindHint:"feedback",explicitness:"explicit",content:r.rule,sourceMessageIndex:0,sourceRole:"assistant",metadata:{appliesTo:r.appliesTo,feedbackKind:"validated_pattern"}}}function ps(r,s){if(r.userId!==s.userId)return!1;if(s.tenantId!==void 0&&r.tenantId!==s.tenantId)return!1;if(s.workspaceId!==void 0&&r.workspaceId!==s.workspaceId)return!1;if(s.agentId!==void 0&&r.agentId!==s.agentId)return!1;return!0}function ro(r){let s=[];if(r.previous.appliesTo!==r.nextAppliesTo)s.push({op:"set",target:"appliesTo",value:r.nextAppliesTo});if(r.previous.rule!==r.nextRule)s.push({op:"set",target:"rule",value:r.nextRule});if(r.previous.why!==r.nextWhy)s.push({op:"set",target:"why",value:r.nextWhy});return s}function so(r){return{artifactType:r.artifactType,canonicalMemoryId:r.canonicalMemoryId,currentContent:r.currentContent,nextContent:r.nextContent,relativePath:r.relativePath,risky:r.risky,scope:r.scope,structuredDelta:r.structuredDelta}}async function Xr(r,s,o){let H=await Tr(r,Dr,{scope:s,includeRuntime:!0},o);return new Map(H.artifacts.map((f)=>[f.relativePath,f]))}async function oo(r){let s=r.now(),o=(I)=>T({adapterId:r.adapterId,artifactType:r.writeInput.artifactType,canonicalMemoryId:I.canonicalMemoryId,failureReasons:I.failureReasons,hostKind:r.hostKind,mode:r.mode,policyApplied:I.policyApplied,relativePath:I.relativePath??r.writeInput.relativePath,risky:I.risky,rollbackPerformed:I.rollbackPerformed,structuredDelta:I.structuredDelta,verificationOutcome:I.verificationOutcome,wroteAt:s});if(!r.writeInput.relativePath.startsWith("playbooks/")||r.writeInput.relativePath.endsWith(".prompt.md")||r.writeInput.relativePath.endsWith(".skill.md"))throw N(`Host adapter does not allow writes for artifact path ${r.writeInput.relativePath}`,o({failureReasons:["Structured delta writeback only supports canonical playbook markdown files."]}));let f=(await Xr(r.memory,r.writeInput.scope,r.language)).get(r.writeInput.relativePath);if(!f)throw N(`Host adapter cannot locate the current artifact ${r.writeInput.relativePath}`,o({failureReasons:["The requested artifact path does not exist in the current exported host surface."]}));let E=r.language.resolveFromText({text:f.content}),w=ns(r.language,E),m=is(f.content,w);if(r.writeInput.content===f.content)return{diagnostics:o({canonicalMemoryId:m??void 0,policyApplied:[],risky:!1,structuredDelta:[]}),status:"noop",updatedArtifact:f};let $;try{$=as(r.writeInput,w)}catch(I){if(I instanceof M)throw N(I.message,o({...I.diagnostics,adapterId:r.adapterId,hostKind:r.hostKind,mode:r.mode,relativePath:r.writeInput.relativePath,provenance:{adapterId:r.adapterId,hostKind:r.hostKind,origin:"host_adapter",wroteAt:s}}));throw I}if(!m)throw N(`Host adapter cannot verify canonical binding for ${r.writeInput.relativePath}`,o({failureReasons:["The current exported playbook is missing canonicalMemoryId and cannot be used for authoritative writeback."]}));if($.canonicalMemoryId!==m)throw N("Host adapter write targets a different canonical record than the current playbook path.",o({canonicalMemoryId:m,failureReasons:["Edited playbook canonicalMemoryId must match the current artifact bound to this path."]}));let A=await r.documentStore.get("feedback",m);if(!A||A.kind!=="validated_pattern"||A.lifecycle!=="active"||!ps(A,r.writeInput.scope))throw N(`Host adapter cannot find writable validated pattern ${m}`,o({canonicalMemoryId:m,failureReasons:["Structured delta writeback only supports the active validated pattern currently bound to this playbook path."]}));let R=us({appliesTo:$.appliesTo,rule:$.rule}),B=[],W=r.language.resolveFromText({...A.source.locale?{locale:A.source.locale}:{},text:A.rule}),K={locale:W.locale,localeSource:A.source.localeSource??W.localeSource,phase:"remember",scope:r.writeInput.scope};if(r.policy?.redact){let I=await r.policy.redact(R,K);if(I.content!==R.content||I.metadata?.appliesTo!==R.metadata.appliesTo)B.push("custom_redact");R={...R,content:I.content,metadata:{...R.metadata,...I.metadata,feedbackKind:"validated_pattern"}}}if(r.policy?.shouldRemember&&!await r.policy.shouldRemember(R,K))throw B.push("custom_shouldRemember"),N("Host adapter write was blocked by policy.",o({canonicalMemoryId:A.id,failureReasons:["Policy rejected the adapter-authored change."],policyApplied:B}));let O=A.rule!==R.content,P=Zr(f.content,w.why),S=Zr(r.writeInput.content,w.why),Y=A.why===void 0&&Gr(S)&&(P.length===0||Gr(P))?void 0:$.why,J=ro({nextAppliesTo:R.metadata.appliesTo,nextRule:R.content,nextWhy:Y,previous:A});if(J.length===0)return{diagnostics:o({canonicalMemoryId:A.id,policyApplied:B,risky:O,structuredDelta:J}),status:"noop",updatedArtifact:f};if(r.policy?.resolveConflict){let I=await r.policy.resolveConflict(qr(A,"feedback"),R,K);if(I.action==="keep_existing")throw B.push("custom_resolveConflict"),N("Host adapter write was blocked by conflict policy.",o({canonicalMemoryId:A.id,failureReasons:[I.reason??"Conflict policy kept the existing canonical memory."],policyApplied:B,risky:O,structuredDelta:J}))}let G="not_run",F;if(O){if(!r.verifyWrite)G="review_required",F="Risky adapter writes require verification before they can be applied.";else{let I=await r.verifyWrite(so({artifactType:r.writeInput.artifactType,canonicalMemoryId:A.id,currentContent:f.content,nextContent:r.writeInput.content,relativePath:r.writeInput.relativePath,risky:O,scope:r.writeInput.scope,structuredDelta:J}));G=I.outcome,F=I.reason}if(G!=="passed")throw N("Host adapter write requires verification.",o({canonicalMemoryId:A.id,failureReasons:[F??"Risky adapter writes require verification before they can be applied."],policyApplied:B,risky:O,structuredDelta:J,verificationOutcome:G}))}let b=br({...A,appliesTo:R.metadata.appliesTo,rule:R.content,source:Qr(A.source),updatedAt:s,why:Y}),U=r.createId(),l=jr({id:U,userId:A.userId,tenantId:A.tenantId,workspaceId:A.workspaceId,agentId:A.agentId,sessionId:r.writeInput.scope.sessionId,kind:"feedback",traceId:`host-write-${U}`,trigger:"governance",modelInfluence:"none",summary:`Host adapter ${r.adapterId} updated validated pattern ${A.id}.`,policyApplied:B,linkedMemoryIds:[A.id],metrics:{},createdAt:s}),j=!1;try{await r.documentStore.set("feedback",A.id,b),await r.documentStore.set(sr,U,l);let _=[...(await Xr(r.memory,r.writeInput.scope,r.language)).values()].find((h)=>h.artifactType==="playbook"&&h.relativePath.endsWith(".md")&&!h.relativePath.endsWith(".prompt.md")&&!h.relativePath.endsWith(".skill.md")&&h.content.includes(`canonicalMemoryId: ${A.id}`))??f;return{diagnostics:o({canonicalMemoryId:A.id,policyApplied:B,risky:O,structuredDelta:J,verificationOutcome:G}),linkedExperienceId:U,status:"applied",updatedArtifact:_}}catch(I){j=!0;try{await r.documentStore.set("feedback",A.id,A),await r.documentStore.delete(sr,U)}catch{j=!1}throw N("Host adapter write failed.",o({canonicalMemoryId:A.id,failureReasons:[I instanceof Error?I.message:String(I)],policyApplied:B,risky:O,rollbackPerformed:j,structuredDelta:J,verificationOutcome:G}))}}function Ho(r,s,o){if(!r.includes(s.artifactType))throw N(`Host adapter does not allow writes for artifact type ${s.artifactType}`,o);throw N(`Structured delta writeback is not implemented yet for artifact type ${s.artifactType}`,o)}function jo(r){let s=rr(r.readableArtifactTypes,zr),o=rr(r.supportedReadableArtifactTypes,Dr),H=rr(r.writableArtifactTypes,[]),f=r.mode??"file-assisted",E=r.now??(()=>new Date().toISOString()),w=r.createId??(()=>crypto.randomUUID()),m=g(r.memory)?.language??hr();if(r.id.trim().length===0)throw Error("host adapter id must not be empty");hs({readableArtifactTypes:s,supportedReadableArtifactTypes:o}),Qs({documentStorePresent:Boolean(r.documentStore),mode:f,readableArtifactTypes:s,writableArtifactTypes:H});let $=Ur(s),A=Ur(H),R=Object.freeze({mode:f,readableArtifactTypes:$,writableArtifactTypes:A}),B=r.hostKind??"generic",W={id:r.id,hostKind:B,capabilities:R,async assessAction(K){let O=Ds(t(K),B),P=await r.memory.exportMemory({scope:O.scope,includeRuntime:Boolean(O.scope.sessionId)}),S=Fr({exported:P,intent:O,language:m}),Y=await Ts({assessment:S,intent:O,memory:r.memory});return{...S,...Y}},async readArtifacts(K){let O=await Tr(r.memory,$,K,m);return{...O,artifacts:O.artifacts.map((P)=>({...P,writable:A.includes(P.artifactType)}))}},async writeArtifact(K){let O=T({adapterId:r.id,artifactType:K.artifactType,hostKind:B,mode:f,relativePath:K.relativePath,wroteAt:E()});if(K.artifactType==="playbook"&&A.includes("playbook"))return oo({adapterId:r.id,createId:w,documentStore:r.documentStore,hostKind:B,language:m,memory:r.memory,mode:f,now:E,policy:r.policy,verifyWrite:r.verifyWrite,writeInput:K});return Ho(A,K,O)}};if(B==="codex"){let K=qs(r.memory)?r.memory:void 0;Br(W,{createBehavioralTraceRecorder:({cue:O,scope:P,traceId:S})=>$r({cue:O,hostKind:"codex",traceId:S??`host-trace-${w()}`,onClose:async(Y)=>{if(!K)return{recorded:!1};return{recorded:(await p({memory:K,scope:P,trace:Y})).recorded}}}),...K?{recordBehavioralTrace:async({scope:O,trace:P})=>{return{recorded:(await p({memory:K,scope:O,trace:P})).recorded}}}:{}})}return Object.freeze(W)}function Mr(r){switch(r.kind){case"command":return{kind:"command",command:r.command,...r.summary?{summary:r.summary}:{}};case"tool_call":return{kind:"tool_call",toolName:r.toolName,...r.payload!==void 0?{payload:r.payload}:{},...r.raw?{raw:r.raw}:{},...r.summary?{summary:r.summary}:{}};case"file_edit":return{kind:"file_edit",operation:r.operation,relativePath:r.relativePath,...r.summary?{summary:r.summary}:{}}}}function fo(r){if(r.kind==="warning")return{kind:"warning",message:r.message};return Mr(r)}function To(r){if(r.assessment.actionId!==r.intent.actionId)throw Error("host action assessment actionId must match the planned intent actionId");let s=Mr(r.intent.action);switch(r.assessment.decision){case"allow":case"allow_with_guidance":return{actionId:r.intent.actionId,blocked:!1,decision:r.assessment.decision,effectiveFirstStep:s,executeOriginalActionNow:!0,guidance:[...r.assessment.guidance],intercepted:!1,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!1};case"review_required":{if(!r.assessment.recommendedFirstStep)throw Error("review_required host action assessments must provide a recommendedFirstStep");return{actionId:r.intent.actionId,blocked:!1,decision:r.assessment.decision,effectiveFirstStep:fo(r.assessment.recommendedFirstStep),executeOriginalActionNow:!1,guidance:[...r.assessment.guidance],intercepted:!0,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!0}}case"blocked":return{actionId:r.intent.actionId,blocked:!0,decision:r.assessment.decision,executeOriginalActionNow:!1,guidance:[...r.assessment.guidance],intercepted:!0,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!1}}}
export{M as Ea,t as Fa,wo as Ga,jo as Ha,To as Ia};
import{Za as S,bb as A0,cb as d0,fb as y0,gb as x0,hb as E0,jb as u,sb as _0}from"./chunk-0h5pry7v.js";import{Ib as f0}from"./chunk-jr0h5wkn.js";function X0(G){return(G.codePointAt(0)??0)>127}function FD(G){let D=0,H=0;for(let $ of G)if(X0($))D+=1;else H+=$.length;return D+Math.ceil(H/4)}function SD(G,D){if(D<=0||G.length===0)return"";let H=0,$=0,M=0;for(let V of G){let j=X0(V),J=H+(j?1:0),Z=M+(j?0:V.length);if(J+Math.ceil(Z/4)>D)break;H=J,$+=V.length,M=Z}return G.slice(0,$)}var K0="tool_outcome",s="tool_outcome.";function n0(G){return encodeURIComponent(G)}function t0(G){return decodeURIComponent(G)}function k(G,D){return`${s}${G}=${n0(D)}`}function o(G){return{...G,args:G.args&&G.args.length>0?[...G.args]:void 0,raw:G.raw?.trim()||void 0}}function q(G){if(G.kind==="warning")return G.raw??G.name;let D=G.args&&G.args.length>0?`(${G.args.join(", ")})`:"";return D.length>0?`${G.name}${D}`:G.raw??G.name}function e0(G){let D=o(G);if(D.args)return{kind:D.kind,name:D.name,args:D.args};return{kind:D.kind,name:D.name,...D.raw?{raw:D.raw}:{}}}function U0(G){return JSON.stringify(e0(G))}function ID(G,D){if(!G||!D)return G===D;return U0(G)===U0(D)}function GG(G){let D=[K0,k("cue",G.cue),k("failure_class",G.failureClass),k("first_action.kind",G.firstAction.kind),k("first_action.name",G.firstAction.name)];if(G.firstAction.args&&G.firstAction.args.length>0)D.push(k("first_action.args",JSON.stringify(G.firstAction.args)));if(G.firstAction.raw)D.push(k("first_action.raw",G.firstAction.raw));if(G.retrievalProfile)D.push(k("retrieval_profile",G.retrievalProfile));if(G.saferAlternative){if(D.push(k("safer_alternative.kind",G.saferAlternative.kind)),D.push(k("safer_alternative.name",G.saferAlternative.name)),G.saferAlternative.args&&G.saferAlternative.args.length>0)D.push(k("safer_alternative.args",JSON.stringify(G.saferAlternative.args)));if(G.saferAlternative.raw)D.push(k("safer_alternative.raw",G.saferAlternative.raw))}return D}function zD(G){let D={...G.result,firstAction:o(G.result.firstAction),saferAlternative:G.result.saferAlternative?o(G.result.saferAlternative):void 0},H=D.saferAlternative?` Safer first action: ${q(D.saferAlternative)}.`:"";return{..._0({id:G.createId(),userId:G.scope.userId,tenantId:G.scope.tenantId,workspaceId:G.scope.workspaceId,agentId:G.scope.agentId,sessionId:G.scope.sessionId,kind:"maintenance",traceId:G.traceId,trigger:"api",modelInfluence:D.modelInfluence,summary:`Behavioral tool outcome for cue "${D.cue}": first action ${q(D.firstAction)} failed with ${D.failureClass}.`+H,outcome:D.outcome??"failure",policyApplied:GG(D),metrics:{accepted:0,rejected:1},linkedEvidenceIds:G.linkedEvidenceIds??[],createdAt:G.createdAt}),kind:"tool_outcome"}}function DG(G){return G.kind==="tool_outcome"||G.policyApplied.includes(K0)}function qD(G){return G}function Q0(G,D){let H=G.get(`${D}.kind`),$=G.get(`${D}.name`);if(!H||!$)return;let M=G.get(`${D}.args`),V=G.get(`${D}.raw`),j;if(M)try{let J=JSON.parse(M);if(Array.isArray(J)&&J.every((Z)=>typeof Z==="string"))j=J}catch{j=void 0}return{kind:H,name:$,...j?{args:j}:{},...V?{raw:V}:{}}}function w0(G){if(!DG(G))return null;let D=new Map;for(let J of G.policyApplied){if(!J.startsWith(s))continue;let[Z,W]=J.slice(s.length).split("=",2);if(!Z||W===void 0)continue;D.set(Z,t0(W))}let H=D.get("cue"),$=D.get("failure_class"),M=Q0(D,"first_action");if(!H||!$||!M)return null;let V=D.get("retrieval_profile");return{cue:H,failureClass:$,firstAction:M,retrievalProfile:V==="coding_agent"||V==="general_chat"?V:void 0,saferAlternative:Q0(D,"safer_alternative")}}function hD(G,D){return{...G,compiledGuidance:D}}function vD(G){return G.compiledGuidance}function HG(G){return 1/(1+Math.exp(-G))}function l(G){let D=G.model.bias+G.features.reduce((H,$,M)=>{return H+$*(G.model.weights[M]??0)},0);return{probability:HG(D),score:D}}function R0(G){if(G.samples.length<4)return G.baseModel;let D=[...G.baseModel.weights],H=G.baseModel.bias,$=G.learningRate??0.18,M=G.epochs??60;for(let V=0;V<M;V+=1)for(let j of G.samples){let J=l({features:j.features,model:{bias:H,featureNames:G.baseModel.featureNames,weights:D}}).probability,Z=j.label-J;H+=$*Z;for(let W=0;W<D.length;W+=1)D[W]=(D[W]??0)+$*Z*(j.features[W]??0)}return{bias:H,featureNames:[...G.baseModel.featureNames],weights:D}}function d(G){return(G??"").replace(/\s+/gu," ").trim()}function L0(G,D=140){let H=d(G);if(H.length<=D)return H;return`${H.slice(0,Math.max(0,D-3)).trimEnd()}...`}function h(G){return[...new Set(G.filter((D)=>D.trim().length>0))]}function $G(G,D,H){return Math.min(H,Math.max(D,G))}function MG(G){let D=G.selections[0]?.exemplar,H=G.selections.some(($)=>{let M=$.exemplar,V=[M.episodeShape.safeCorrectedMove,M.episodeShape.relevantPriorMove,M.episodeShape.observedOutcome].join(" ");return M.intentCue.query.constraintTypes.includes("precondition")||M.intentCue.query.actionType==="guarded_api"||/\bcheck\b.+\bonly\s+(?:if|when)\b/iu.test(V)});if(G.queryIntent.constraintTypes.includes("formula")||G.queryIntent.actionType==="symbolic_rule")return"symbolic_rule_execution";if(G.surfaceFamily==="text_response"&&(H||G.queryIntent.constraintTypes.includes("precondition")||G.queryIntent.actionType==="guarded_api"))return"conditional_precondition";if(G.surfaceFamily==="host_action"&&(G.queryIntent.constraintTypes.includes("arg_order")||G.queryIntent.constraintTypes.includes("exact_action")||Boolean(D?.exactSurface?.value)||Boolean(G.queryIntent.exactSlots.commandName)))return D?.exactSurface?.value&&G.selections.length===1&&D.intentCue.query.exactSlots.commandName===G.queryIntent.exactSlots.commandName?"exact_surface_copy":"slot_rebinding";if(G.queryIntent.constraintTypes.includes("precondition")||G.queryIntent.actionType==="guarded_api")return"conditional_precondition";if(G.queryIntent.actionType==="format_contract")return"exact_format_contract";if(G.queryIntent.constraintTypes.includes("style")||G.queryIntent.actionType==="voice_style")return"exact_format_contract";if(G.queryIntent.constraintTypes.includes("path_root")||G.queryIntent.constraintTypes.includes("safe_alternative")||G.queryIntent.constraintTypes.includes("url_shape")||G.queryIntent.constraintTypes.includes("analogy"))return"hard_constraint_contract";if(D?.exactSurface?.value&&G.selections.length===1&&D.confidence>=0.72)return"exact_surface_copy";return"slot_rebinding"}function jG(G){let D=G.selections[0]?.exemplar;if(!D)return[];let H=[],$=D.intentCue.query.exactSlots;if($.commandName)H.push(`command=${$.commandName}`);if($.argOrderSignature)H.push(`arg_order=${$.argOrderSignature}`);if($.urlHost)H.push(`url_host=${$.urlHost}`);if($.pathRoot)H.push(`path_root=${$.pathRoot}`);if(D.exactSurface?.kind)H.push(`surface_kind=${D.exactSurface.kind}`);if(D.exactSurface?.formatPrefixes?.length)H.push(`required_prefix=${D.exactSurface.formatPrefixes[0]}`);if(D.exactSurface?.formatSuffixes?.length)H.push(`required_suffix=${D.exactSurface.formatSuffixes[0]}`);if($.styleMarkers.length>0)H.push(`style=${$.styleMarkers.join(",")}`);if(G.queryIntent.constraintTypes.includes("precondition"))H.push("must_check_precondition");if(G.selections.some((M)=>M.exemplar.intentCue.query.constraintTypes.includes("precondition")||M.exemplar.intentCue.query.actionType==="guarded_api"))H.push("must_check_precondition");if(G.computedResponseRule)H.push(G.computedResponseRule.kind==="recurrence"?`formula=${G.computedResponseRule.sequenceName}(n)=${G.computedResponseRule.expression}`:`formula=${G.computedResponseRule.leftVariable}${G.computedResponseRule.operatorSymbol}${G.computedResponseRule.rightVariable}=${G.computedResponseRule.expression}`);if(D.exactSurface?.value)H.push(`surface=${L0(D.exactSurface.value,96)}`);return h(H)}function VG(G){let D=[];if(G.exactSlots.filename)D.push(`filename=${G.exactSlots.filename}`);if(G.exactSlots.extension)D.push(`extension=${G.exactSlots.extension}`);if(G.exactSlots.pathRoot)D.push(`path_root=${G.exactSlots.pathRoot}`);if(G.exactSlots.urlHost)D.push(`url_host=${G.exactSlots.urlHost}`);if(G.exactSlots.urlPath)D.push(`url_path=${G.exactSlots.urlPath}`);if(G.exactSlots.commandName)D.push(`command=${G.exactSlots.commandName}`);if(G.exactSlots.argOrderSignature)D.push(`arg_order=${G.exactSlots.argOrderSignature}`);if(G.exactSlots.operatorSymbols.length>0)D.push(`operators=${G.exactSlots.operatorSymbols.join(",")}`);if(G.exactSlots.styleMarkers.length>0)D.push(`style=${G.exactSlots.styleMarkers.join(",")}`);return h(D)}function JG(G){for(let D of G){let H=[D.exemplar.episodeShape.cue,D.exemplar.episodeShape.relevantPriorMove,D.exemplar.episodeShape.safeCorrectedMove,D.exemplar.exactSurface?.value];for(let $ of H){let M=d($).replace(/,\s*with\s+[A-Z][A-Za-z0-9_]*\((-?\d+)\)\s*=.+$/u,"."),V=A0(M);if(V)return V}}return}function r(G){return d(G).replace(/[^A-Za-z0-9_]+/gu,"_").replace(/^_+|_+$/gu,"").toLowerCase()}function ZG(G){let D=r(G??"value");if(/(?:payload|packet|query|text|term|tag)/u.test(D))return"<terms>";if(/(?:qty|quantity|count|amount|number)/u.test(D))return"<qty>";if(/(?:path|file|filename)/u.test(D))return"<filename>";if(/(?:item|name|label)/u.test(D))return"<item>";if(/(?:id|key|token|query|value|term|record)/u.test(D))return"<id>";return`<${D||"value"}>`}function f(G,D,H){return G.replace(new RegExp(`(['"])(?:${D})\\1\\s*:\\s*(['"])[^'"]+\\2`,"giu"),($)=>$.replace(/(['"])[^'"]+\1\s*$/u,`$1${H}$1`))}function T0(G,D){let H=r(D??""),$=G;$=f($,"query|value|term|terms|text|tag|tags|record","<terms>"),$=f($,"id|key|token","<id>"),$=f($,"path|file|filename","<filename>"),$=f($,"item|name|label","<item>"),$=$.replace(/(['"])(?:qty|quantity|count|amount|number)\1\s*:\s*\d+/giu,(V)=>V.replace(/\d+$/u,"<qty>"));let M=$.match(/^(['"])([^'"]+)\1$/u);if(M){let V=M[1],j=M[2]??"";if(/(?:auth|guard|mode|buffer)/u.test(H))return $;if(/(?:path|file|filename)/u.test(H)||/^(?:\/|~\/)/u.test(j))return`${V}<filename>${V}`;if(/(?:qty|quantity|count|amount|number)/u.test(H))return"<qty>";if(/(?:item|name|label)/u.test(H))return`${V}<item>${V}`;if(/(?:payload|packet|query|text|term|terms|tag|tags|record)/u.test(H))return`${V}<terms>${V}`;if(/(?:id|key|token)/u.test(H))return`${V}<id>${V}`}if(/^\d+$/u.test($)&&/(?:qty|quantity|count|amount|number)/u.test(H))return"<qty>";return $}function WG(G){return G.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function YG(G,D){if(!/\b(?:auth|key|token)\b/iu.test(D))return;return[...G.matchAll(/\b([A-Z][A-Z0-9_]*\d[A-Z0-9_]*)\b/gu)].map((H)=>H[1]??"").filter((H)=>H.length>0).sort((H,$)=>$.length-H.length)[0]}function B0(G,D=""){let H=YG(G,D);if(H)return G.replace(new RegExp(WG(H),"gu"),"<token>");let M=[...[...G.matchAll(/\b([A-Z][A-Z0-9_]{2,})\b/gu)].map((V)=>V[1]??"")].sort((V,j)=>j.length-V.length).find((V,j,J)=>V.length>0&&J.indexOf(V)===j&&J.filter((Z)=>Z===V).length>=2);if(!M)return G;return G.replace(new RegExp(M,"gu"),"<token>")}function XG(G){let D=G.match(/^(.+\|\s*FILTER\s+)([A-Za-z_][A-Za-z0-9_.-]*)\s*(>=|<=|=|>|<)\s*(?:-?\d+(?:\.\d+)?|'[^']+'|"[^"]+")$/u);if(!D?.[1])return;return`${D[1]}<field> <operator> <value>`}function UG(G,D){if(!/^[^\s]+\s+\|[^|]+\|(?:\|[^|]+\|)*$/u.test(G))return G;let H=/\bpipe\s+path\b/iu.test(D)?"|path|":"|folder|";return G.replace(/\|[^|]+\|(?:\|[^|]+\|)*/u,H)}function N0(G){let D=G.match(/\b(?:required\s+)?(?:argument\s+)?order\s*(?:is|:)\s*([^.;]+)/iu)?.[1]??G.match(/\border\s+is\s+[^:.;]*:\s*([^.;]+)/iu)?.[1]??G.match(/\b((?:destination|target|archive|source|owner|permissions?|perms?|mode|flags?|compression|tag|query_payload|data_packet|preface|buffer|auth)(?:\s+(?:first|second|third|fourth|last|finally))?(?:(?:\s*,?\s*(?:then|and finally|finally|,)\s*)(?:destination|target|archive|source|owner|permissions?|perms?|mode|flags?|compression|tag|query_payload|data_packet|preface|buffer|auth)(?:\s+(?:first|second|third|fourth|last|finally))?)+)/iu)?.[1];if(!D)return[];return D.split(/\s*(?:,|>|then|and finally|finally|before)\s*/iu).map((H)=>r(H.replace(/\b(?:first|second|third|fourth|fifth|last|finally)\b/giu,""))).filter(Boolean)}function b0(G,D){let H=XG(G);if(H)return H;let $=G.match(/^([A-Za-z_][A-Za-z0-9_]*)\((.*)\)$/u);if(!$)return B0(UG(G,D),D);let[,M,V=""]=$,j=S(V),J=N0(D);if(J.length===j.length&&J.length>0&&j.every((_)=>!/^[A-Za-z_][A-Za-z0-9_]*\s*=/u.test(_)))return`${M}(${J.join(", ")})`;let Z=j.length===2&&j.every((_)=>/^['"](?:~\/|\/)[^'"]+['"]$/u.test(_)),W=j[0]?.replace(/^['"]|['"]$/gu,"")??"",Y=j[1]?.replace(/^['"]|['"]$/gu,"")??"",U=/(?:^|\/)(?:dest|destination|target)(?:\/|$)/iu.test(W),Q=/(?:^|\/)(?:src|source)(?:\/|$)/iu.test(Y);if(Z&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(D)&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(D))return`${M}(destination_path, source_path)`;if(Z&&/\bdestination\b/iu.test(D)&&/\bsource\b/iu.test(D)&&U&&Q)return`${M}(destination_path, source_path)`;if(Z&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(D)&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(D))return`${M}(source_path, destination_path)`;let K=j.map((_)=>{let w=_.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=(.+)$/u);if(!w)return T0(_,void 0);let b=w[1];return`${b}=${T0(w[2].trim(),b)}`});return B0(`${M}(${K.join(", ")})`,D)}function QG(G,D){let H=D?.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),$=H?[new RegExp(`\\b${H}\\((?:[^()]|\\([^)]*\\))*\\)`,"u"),new RegExp(`["'\`](${H}\\s+\\|[^"'\`]+\\|)["'\`]`,"u")]:[/\b[A-Za-z_][A-Za-z0-9_]*\((?:[^()]|\([^)]*\))*\)/u,/["'`]([A-Za-z_][A-Za-z0-9_]*\s+\|[^"'`]+\|)["'`]/u];for(let M of $){let V=G.match(M),j=V?.[1]??V?.[0];if(j)return b0(j.trim(),G)}return}function _G(G){if(/(?:source|destination|target|archive).*path|path.*(?:source|destination|target|archive)/u.test(G))return G;if(/(?:path|file|filename)/u.test(G))return`${G}='<filename>'`;if(/(?:payload|packet|query|record|value|term|text|tag)/u.test(G))return`${G}={'value': '<terms>'}`;if(/(?:id|key|token)/u.test(G))return`${G}={'value': '<id>'}`;if(/(?:item|name|label)/u.test(G))return`${G}='<item>'`;if(/(?:qty|quantity|count|amount|number)/u.test(G))return`${G}=<qty>`;let D=ZG(G);return`${G}=${D}`}function KG(G){if(!G.commandName)return;if(/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(G.move)&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(G.move))return`${G.commandName}(destination_path, source_path)`;if(/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(G.move)&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(G.move))return`${G.commandName}(source_path, destination_path)`;let D=N0(G.move);if(D.length===0)return;return`${G.commandName}(${D.map(_G).join(", ")})`}function wG(G){if(G.surfaceFamily!=="host_action")return;let D=G.selections[0]?.exemplar,H=G.selections.find((J)=>J.exemplar.exactSurface?.kind==="action")?.exemplar,$=H?.intentCue.query.exactSlots.commandName??D?.intentCue.query.exactSlots.commandName??G.queryIntent.exactSlots.commandName,M=d(H?.episodeShape.safeCorrectedMove??H?.episodeShape.relevantPriorMove??D?.episodeShape.safeCorrectedMove??D?.episodeShape.relevantPriorMove),V=H?.exactSurface?.kind==="action"?H.exactSurface.value:void 0;if(V)return b0(V,M);let j=QG(M,$);if(j)return j;return KG({commandName:$,move:M})}function k0(G){if(G.selections.length===0)return;let D=h(G.selections.map((Q)=>Q.prototypeId)),H=h(G.selections.map((Q)=>Q.exemplar.id)),$=JG(G.selections),M=MG({queryIntent:G.queryIntent,selections:G.selections,surfaceFamily:G.surfaceFamily}),V=wG({queryIntent:G.queryIntent,selections:G.selections,surfaceFamily:G.surfaceFamily}),j=G.selections.reduce((Q,K)=>Q+K.probability,0)/G.selections.length,J=Math.min(0.22,G.conflictPrototypeIds.length*0.06),Z=$G(j-J,0,0.99),W=G.surfaceFamily==="host_action"&&Boolean(V),Y=Z<0.58?"abstain":W?"transient_executor":M==="exact_surface_copy"?"model_only":Z>=0.66?"transient_executor":"model_only",U=G.selections[0]?.exemplar;return{applicability:L0(G.queryIntent.goal,96),canonicalActionTemplate:V,commandName:G.queryIntent.exactSlots.commandName??U?.intentCue.query.exactSlots.commandName,confidence:Z,conflictingPrototypeIds:[...G.conflictPrototypeIds],constraintTypes:h([...G.queryIntent.constraintTypes,...G.selections.flatMap((Q)=>Q.exemplar.intentCue.query.constraintTypes)]),computedResponseRule:$,executionMode:Y,mappingType:M,stableFields:jG({computedResponseRule:$,queryIntent:G.queryIntent,selections:G.selections}),supportingExemplarIds:H,supportingPrototypeIds:D,surfaceFamily:G.surfaceFamily,taskFamily:G.queryIntent.actionType,varyingFields:VG(G.queryIntent)}}function O0(G){let D=G.hypothesis;if(!D||D.executionMode!=="transient_executor")return{lines:[],mode:"none"};switch(D.mappingType){case"symbolic_rule_execution":case"symbolic_formula":{let H=E0({query:G.query,rule:D.computedResponseRule});if(!H)return{lines:["Use the observed formula pattern and substitute the current probe values before answering."],mode:"hint"};return{computedResponse:H,lines:[`Probe-specific computed value: ${H}`],mode:"computed"}}case"slot_rebinding":{if(D.surfaceFamily==="host_action"&&D.canonicalActionTemplate){let $=u({query:G.query,template:D.canonicalActionTemplate});if($)return{computedResponse:$,lines:[`Emit exactly: ${$}`],mode:"computed"}}let H=[D.commandName?`Keep the command or tool surface as ${D.commandName}.`:"",D.stableFields.find(($)=>$.startsWith("arg_order="))?`Preserve ${D.stableFields.find(($)=>$.startsWith("arg_order="))?.replace("arg_order=","argument order ")}.`:"","Rebind only the probe-specific slot values; do not invent a different action family."].filter(Boolean);return{lines:H,mode:H.length>0?"hint":"none"}}case"hard_constraint_contract":return{lines:["Apply the observed hard response contract directly to the answer surface.","Prefer the safe replacement or constrained path/protocol over the failed surface."],mode:"hint"};case"exact_format_contract":return{lines:["Preserve the observed exact format, required prefix/suffix, voice, and ordering."],mode:"hint"};case"style_contract":return{lines:["Keep the response inside the observed style contract for this probe."],mode:"hint"};case"conditional_precondition":case"guarded_decision":return{lines:["Check the precondition implied by the prior examples before proceeding.","If the precondition is not satisfied, fall back to a warning or defer instead of pretending success."],mode:"hint"};case"exact_surface_copy":if(D.surfaceFamily==="host_action"&&D.canonicalActionTemplate){let H=u({query:G.query,template:D.canonicalActionTemplate});if(H)return{computedResponse:H,lines:[`Emit exactly: ${H}`],mode:"computed"}}return{lines:["Keep the same exact surface family, only adapting the probe-specific slots when necessary."],mode:"hint"}}}function F0(G){let D=G.hypothesis;if(!D)return;let H=[];if(D.stableFields.length>0)H.push(["Observed stable pattern:",...D.stableFields.slice(0,4).map(($)=>`- ${$}`)].join(`
`));if(D.varyingFields.length>0)H.push(["Probe-specific varying slots:",...D.varyingFields.slice(0,4).map(($)=>`- ${$}`)].join(`
`));if(G.execution.lines.length>0)H.push(["Probe-conditioned execution:",...G.execution.lines.map(($)=>`- ${$}`)].join(`
`));return H.length>0?H.join(`
`):void 0}function S0(G){let D=O0({hypothesis:G.hypothesis,query:G.query});return{...D,hypothesisSketch:F0({execution:D,hypothesis:G.hypothesis})}}var P0=0.08,v=0.58,RG={bias:-0.85,featureNames:["lexicalSimilarity","semanticSimilarity","intentCompatibility","surfaceCompatibility","exactSlotOverlap","exactSurfaceMatch","correctionSuccessPrior","interferenceRisk","recencySupport","repetitionSupport","cueCompatibility"],weights:[1.15,0.95,1.45,0.7,1.35,1.1,0.9,-1.2,0.3,0.5,1.25]},TG=0.28,BG=0.1,AG=0.05,EG=0.18,P=120,LG=180,NG=2,L=f0();function B(G,D=LG){let H=G.replace(/\s+/gu," ").trim();if(H.length<=D)return H;return`${H.slice(0,Math.max(0,D-3)).trimEnd()}...`}function R(G){return(G??"").replace(/\s+/gu," ").trim()}function A(G,D=L){if(!G?.trim())return;let H=D.resolveFromText({text:G});return D.analyzeBehavioralRule(G,H)}function O(G){let D=L.resolveFromText({text:G});return L.tokenize(G,D,{excludeStopwords:!0})}function E(G){return[...new Set(G.filter((D)=>D.trim().length>0))]}function bG(G){return(G.match(/["“](.+?)["”]/u)??G.match(/'([^']+)'/u))?.[1]?.trim()}function N(G,D){if(G.length===0||D.length===0)return 0;let H=new Set(D);return G.filter((M)=>H.has(M)).length/Math.max(G.length,D.length)}function F(G){let D=A(G),H=D?.semanticCues??[];return E([...D?.hostAction?["operation_surface"]:[],...D?.hostAction?.destination||D?.hostAction?.sources?["path_constraint"]:[],...H.map(($)=>{switch($){case"failure":return"failure_signal";case"permission_failure":return"permission_failure";case"timeout":return"timeout_failure";case"unsafe":return"unsafe_or_deprecated";case"inhibition_replacement":return"inhibition_replacement";case"safe_fallback":return"safe_fallback";case"path":return"path_constraint";case"api":case"command":case"operation":return"operation_surface";case"argument_order":return"slot_order_contract";case"url":return"url_protocol";case"filetype":return"filetype_contract";case"format":return"format_contract";case"analogy":return"style_simplification";case"voice":return"voice_contract";case"symbolic":return"symbolic_rule";case"precondition":return"precondition_contract";case"brevity":return"brevity_contract";case"style":return"style_contract"}})])}function j0(G){return E([G.actionType,...G.constraintTypes,...G.entityTypes,...F(G.goal)])}function kG(G){let D=G.representative;return E([G.intentCue.query.actionType,...G.constraintTypes,...G.intentCue.query.entityTypes,...G.interferenceTags,...F(D.retrievalText),...F(D.episodeShape.cue),...F(D.episodeShape.observedOutcome),...F(D.episodeShape.relevantPriorMove),...F(D.episodeShape.safeCorrectedMove)])}function m0(G,D){return N(j0(G),kG(D))}function C(G){let D=R(G);return D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s*\(/u)?.[1]??D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s+\|[^|]+\|/u)?.[1]??D.match(/\b([A-Z][A-Z0-9_]*)\s+[A-Za-z0-9_]+\s+\|/u)?.[1]??A(G)?.commandName}function OG(G){let D=R(G),H=D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\([^)]*\)/u)?.[0]??D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s+\|[^|]+\|/u)?.[0]??D.match(/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|\s+[A-Z][A-Z0-9_]*\s+[^.]+/u)?.[0]??D.match(/['"`]([A-Za-z_][A-Za-z0-9_@]*(?:\s+[A-Za-z0-9_./<>{}\[\]'":,@|=-]+){0,8})['"`]/u)?.[1];return H?I(H.trim()):void 0}function FG(G){let D=A(G),H=new Set(D?.semanticCues??[]);if(D?.hostAction||C(G)||H.has("argument_order"))return"structured_action";if(H.has("precondition"))return"guarded_api";if(H.has("command"))return"structured_action";if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)&&(H.has("symbolic")||/=/u.test(G)))return"symbolic_rule";if(H.has("analogy"))return"analogy_explanation";if(H.has("url"))return"url_rewrite";if(H.has("path"))return"path_redirect";if(H.has("api"))return"api_route";if(H.has("format"))return"format_contract";if(H.has("symbolic"))return"symbolic_rule";if(H.has("voice"))return"voice_style";return"general_response"}function SG(G){let D=A(G),H=new Set(D?.semanticCues??[]),$=[];if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)||H.has("symbolic"))$.push("symbolic");if(H.has("url"))$.push("url");if(D?.hostAction||C(G)||H.has("command")||H.has("operation"))$.push("command");if(H.has("path")||D?.hostAction?.destination||D?.hostAction?.sources)$.push("path");if(H.has("api"))$.push("api");if(H.has("analogy"))$.push("analogy");if(H.has("format"))$.push("format");if(H.has("command")&&/\|/u.test(G))$.push("query");if(H.has("voice"))$.push("voice");return E($)}function I(G){return G.replace(/[.,;:!?。]+$/u,"")}function C0(G){return[...R(G).matchAll(/https?:\/\/[^\s),;]+/gu)].map((D)=>I(D[0]??"")).filter((D)=>D.length>0)}function I0(G){let D=[];for(let H of R(G).matchAll(/\bhttps?\b/giu)){let $=H[0]?.toLowerCase();if(($==="http"||$==="https")&&!D.includes($))D.push($)}return D}function n(G){return[...R(G).matchAll(/(?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._-]/gu)].map((D)=>I(D[0]??"")).filter((D)=>D.length>0)}function t(G){let D=I(G.trim());if(!D.startsWith("/"))return;let H=D.split("/").filter(Boolean);return H[0]?`/${H[0]}`:void 0}function PG(G){let D=I(G.trim());if(!D.startsWith("/")&&!D.startsWith("~/"))return;let H=D.lastIndexOf("/");if(H<0)return;return D.slice(0,H+1)}function c0(G){return I(G.trim()).split("/").filter(Boolean).at(-1)}function CG(G){let D=c0(G);if(!D)return;let H=D.lastIndexOf(".");return H<=0?void 0:D.slice(H)}function IG(G){let D=A(G),H=new Set(D?.semanticCues??[]),$=[];if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)||H.has("symbolic"))$.push("formula");if(H.has("url"))$.push("url_shape");if(H.has("path")||D?.hostAction?.destination||D?.hostAction?.sources)$.push("path_root");if(H.has("argument_order"))$.push("arg_order");if(H.has("safe_fallback")||H.has("inhibition_replacement"))$.push("safe_alternative");if(H.has("analogy"))$.push("analogy");if(H.has("precondition"))$.push("precondition");if(H.has("style")||H.has("voice"))$.push("style");if(D?.hostAction||C(G)||H.has("argument_order")||H.has("command"))$.push("exact_action");return E($)}function V0(G){let D=R(G);if(A(D)?.hostAction||C(D)||/\b[a-z_][a-z0-9_]*\([^)]*\)/iu.test(D))return"host_action";return"text_response"}function zG(G,D){let H=R(G),$=H.match(/https?:\/\/([^\s/]+)(\/[^\s)]*)?/u),M=H.match(/(?:~\/|\/)[A-Za-z0-9._/-]+/u)?.[0],V=H.match(/\b([A-Za-z_][A-Za-z0-9_]*)\((.+)\)/u),J=((V?.[2])?S(V[2]).map((Y)=>Y.trim()):[]).map((Y)=>Y.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/u)?.[1]??"").filter(Boolean),Z=[...H.matchAll(/[⊗⊕⊖⊙]|->|=>|[+*=-]/gu)].map((Y)=>Y[0]).filter((Y,U,Q)=>Q.indexOf(Y)===U),W=A(H)?.semanticCues?.includes("voice")?["voice"]:[];return{argNames:J,argOrderSignature:J.length>0?J.join(">"):void 0,commandName:D==="host_action"?V?.[1]??C(H):void 0,extension:M?CG(M):void 0,filename:M?c0(M):void 0,operatorSymbols:Z,pathRoot:M?t(M):void 0,styleMarkers:W,urlHost:$?.[1],urlPath:$?.[2]}}function y(G){return[G.commandName??"",G.argOrderSignature??"",G.urlHost??"",G.urlPath??"",G.pathRoot??"",G.filename??"",G.extension??"",G.operatorSymbols.join(","),G.styleMarkers.join(",")].join("\x02")}function J0(G){let D=R(G);if(!D)return;let H=D.match(/\b([A-Za-z_][A-Za-z0-9_]*)\((.+)\)/u);if(H?.[0]){let Y=S(H[2]).map((U)=>U.trim()).filter(Boolean);return{kind:"action",value:B(H[0],P),...Y&&Y.length>0?{args:Y}:{}}}let $=OG(D);if($)return{kind:$.includes("|")||/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|/u.test($)||/\b[A-Za-z_][A-Za-z0-9_@]*\s+[A-Za-z0-9_./<>{}\[\]'":,@|=-]+/u.test($)?"action":"text",value:B($,P)};let M=D.match(/https?:\/\/[^\s)]+/u);if(M?.[0])return{kind:"url",value:B(M[0],P)};let V=D.match(/(?:~\/|\/)[A-Za-z0-9._/-]+/u);if(V?.[0])return{kind:"path",value:B(V[0],P)};let j=A(D)?.formatSurface,J=j?.prefixes??[],Z=j?.suffixes??[];if(J.length>0||Z.length>0)return{formatPrefixes:J,formatSuffixes:Z,kind:"format",value:B([...J,...Z].join(" / "),P)};let W=bG(D);if(W)return{kind:"text",value:B(W,P)};return}function x(G,D){let H=R(G);return{actionType:FG(G),constraintTypes:IG(G),entityTypes:SG(G),exactSlots:zG(G,D),goal:B(H,96),goalTokens:O(G).slice(0,12),requestedSurface:D}}function qG(G,D){return{query:x(G,D)}}function hG(G){return[`cue: ${B(G.cue)}`,`move: ${B(G.successfulMove)}`,`outcome: ${B(G.observedOutcome)}`,G.safeCorrectedMove?`corrected: ${B(G.safeCorrectedMove)}`:void 0,G.exactSurface?`surface: ${G.exactSurface.value}`:void 0].filter(Boolean).join(" | ")}function vG(G,D){let H=O(G),$=D?O(D.value):[],M=new Set($);return E([...H.filter((V)=>!M.has(V)),...F(G)])}function gG(G){let D=G.source==="tool_outcome"?0.9:G.source==="runtime_buffer"?0.8:0.55;if(G.exactSurface)D+=0.1;if(G.hasCorrection)D+=0.08;if(G.successfulMove.length>=16)D+=0.05;return Math.min(0.98,D)}function m(G){let D=B(G.observedOutcome),H=B(G.successfulMove),$=G.safeCorrectedMove?B(G.safeCorrectedMove):void 0,M=$?`${G.cue} ${$}`:`${G.cue} ${G.successfulMove}`,V=qG(M,G.surfaceFamily);return{confidence:gG({exactSurface:G.exactSurface,hasCorrection:Boolean(G.safeCorrectedMove),source:G.source,successfulMove:G.successfulMove}),createdAt:G.createdAt,episodeShape:{cue:B(G.cue),observedOutcome:D,relevantPriorMove:H,...$?{safeCorrectedMove:$}:{}},exactSurface:G.exactSurface,id:G.id,intentCue:V,interferenceTags:vG(M,G.exactSurface),retrievalText:hG({cue:G.cue,exactSurface:G.exactSurface,observedOutcome:D,safeCorrectedMove:$,successfulMove:H}),scope:G.scope,source:G.source,sourceIds:E(G.sourceIds),surfaceFamily:G.surfaceFamily,transferMode:"episodic_only"}}function s0(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.factPolarity==="negative"||$.unresolved?D:void 0}function z0(G){let D=R(G),H=L.resolveFromText({text:D});if(!L.analyzeContent(D,H).correctionCue)return;return D.match(/^[^::]+[::]\s*(.+)$/u)?.[1]?.trim()??D}function fG(G){let D=R(G),H=L.resolveFromText({text:D});return L.analyzeContent(D,H).correctionCue}function dG(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.correctionCue||$.feedbackKind==="dont"||$.feedbackKind==="prefer"}function yG(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.factPolarity==="positive"||$.feedbackKind==="validated_pattern"?D:void 0}function xG(G){let D=Boolean(G.failureOutcome),H=Math.min(G.messages.length-1,G.startIndex+16);for(let $=G.startIndex;$<H;$+=1){let M=G.messages[$],V=G.messages[$+1];if(M?.role!=="user"||V?.role!=="assistant")continue;let j=G.messages[$+2];if(j?.role==="system"?s0(j.content):void 0){D=!0;continue}let Z=j?.role==="system"?yG(j.content):void 0;if(D&&(Z||fG(M.content)||dG(M.content)))return R(V.content)}return}function e(G){let D=[];for(let H=0;H<G.messages.length-1;H+=1){let $=G.messages[H],M=G.messages[H+1];if($?.role!=="user"||M?.role!=="assistant")continue;let V=R($.content),j=R(M.content);if(!V||!j)continue;let J=G.messages[H+2],Z=G.messages[H+3],W=G.messages[H+4],Y=J?.role==="system"?s0(J.content):void 0,U=J?.role==="system"?z0(J.content):void 0,Q=!U&&Z?.role==="system"?z0(Z.content):void 0,K=U??Q,w=xG({failureOutcome:Y,messages:G.messages,startIndex:H+3})??K;if(Y&&!w)continue;let b=w||j,z=G.surfaceHint??V0(b),W0=J0(b),X=w?Y?`The earlier move failed (${B(Y)}), and a later correction clarified the safer successful move.`:"A later correction clarified the safer successful move for the same kind of request.":"The earlier response established a successful way to handle the same kind of request.";D.push(m({createdAt:void 0,cue:V,exactSurface:W0,id:`${G.prefix}-${H}`,observedOutcome:X,safeCorrectedMove:w,scope:G.scope,source:"runtime_buffer",sourceIds:E([`${G.prefix}:${H}`,J?`${G.prefix}:${H+2}`:"",Z?`${G.prefix}:${H+3}`:"",W?`${G.prefix}:${H+4}`:""]),successfulMove:b,surfaceFamily:z}))}return D}function mG(G){let D=[];for(let H of G.archives){if(H.normalizedTranscript){let J=H.normalizedTranscript.split(/\n+/u).map((Z)=>{let W=Z.indexOf(":");if(W<=0)return null;return{content:Z.slice(W+1).trim(),role:Z.slice(0,W).trim().toLowerCase()}}).filter((Z)=>Boolean(Z));D.push(...e({messages:J,prefix:`archive-${H.id}`,scope:G.scope,surfaceHint:G.surfaceHint}));continue}let $=Array.isArray(H.keyDecisions)?H.keyDecisions:[],M=Array.isArray(H.unresolvedItems)?H.unresolvedItems:[],V=R(H.summary),j=R($[0]??H.summary);if(!V||!j)continue;D.push(m({createdAt:H.archivedAt,cue:V,exactSurface:J0(j),id:`archive-${H.id}`,observedOutcome:M.length===0?"The archived interaction resolved the issue without leaving open loops.":`The archived interaction still left these open loops: ${M.join(", ")}`,scope:G.scope,source:"archive",sourceIds:[H.id],successfulMove:j,surfaceFamily:G.surfaceHint??V0(j)}))}return D}function cG(G){let D=[];for(let H of G.episodes){let $=Array.isArray(H.keyDecisions)?H.keyDecisions:[],M=Array.isArray(H.unresolvedItems)?H.unresolvedItems:[],V=R(H.summary),j=R($[0]??H.summary);if(!V||!j)continue;D.push(m({createdAt:H.createdAt,cue:V,exactSurface:J0(j),id:`episode-${H.id}`,observedOutcome:M.length===0?"The episode captured a resolved successful response pattern.":`The episode preserved these remaining caveats: ${M.join(", ")}`,scope:G.scope,source:"episode",sourceIds:[H.id],successfulMove:j,surfaceFamily:G.surfaceHint??V0(j)}))}return D}function sG(G){let D=[];for(let H of G.memoryExport.durable.experiences){let $=w0(H);if(!$?.saferAlternative)continue;let M=q($.saferAlternative);D.push(m({createdAt:H.createdAt,cue:$.cue,exactSurface:{args:$.saferAlternative.args,kind:"action",value:M},id:`tool-outcome-${H.id}`,observedOutcome:`The earlier first action ${q($.firstAction)} failed, and the safer alternative succeeded better for this cue.`,safeCorrectedMove:M,scope:{agentId:H.agentId,tenantId:H.tenantId,userId:H.userId,workspaceId:H.workspaceId},source:"tool_outcome",sourceIds:[H.id,...H.sourceTraceIds],successfulMove:M,surfaceFamily:G.surfaceHint??"host_action"}))}return D}function oG(G){let D=new Map;for(let H of G){let $=[H.surfaceFamily,H.episodeShape.cue.toLowerCase(),H.episodeShape.relevantPriorMove.toLowerCase(),H.exactSurface?.value.toLowerCase()??""].join("\x00"),M=D.get($);if(!M||H.confidence>M.confidence)D.set($,H)}return[...D.values()]}function lG(G){return[G.surfaceFamily,G.intentCue.query.actionType,G.intentCue.query.constraintTypes.join(","),G.intentCue.query.entityTypes.join(","),y(G.intentCue.query.exactSlots),G.exactSurface?.kind??"none",G.exactSurface?.value.toLowerCase()??""].join("\x01")}function uG(G){return G.reduce((D,H)=>{return D+(H.episodeShape.safeCorrectedMove?1.2:1)},0)}function rG(G){let D=new Map;for(let H of G){let $=lG(H),M=D.get($)??[];M.push(H),D.set($,M)}return[...D.values()].map((H,$)=>{let M=[...H].sort((J,Z)=>{if(J.confidence!==Z.confidence)return Z.confidence-J.confidence;return(Z.createdAt??"").localeCompare(J.createdAt??"")})[0],V=H.length,j=H.length>=NG?"prototype_bounded":M.transferMode;return{confidence:Math.min(0.99,M.confidence+Math.min(0.12,H.length*0.04)),constraintTypes:M.intentCue.query.constraintTypes,exactSlotSignature:y(M.intentCue.query.exactSlots),exemplars:H,exactSurface:M.exactSurface,hardNegativeIds:[],id:`prototype-${$+1}`,intentCue:M.intentCue,interferenceTags:E(H.flatMap((J)=>J.interferenceTags)),representative:M,repetitionSupport:V,successSupport:uG(H),surfaceFamily:M.surfaceFamily,transferMode:j}})}function q0(G){return G?`${G.kind}:${G.value.toLowerCase()}`:"none"}function pG(G){let D=[];for(let H=0;H<G.length;H+=1){let $=G[H];for(let M=H+1;M<G.length;M+=1){let V=G[M];if($.surfaceFamily!==V.surfaceFamily)continue;if(N($.intentCue.query.goalTokens,V.intentCue.query.goalTokens)<TG)continue;let J=q0($.exactSurface)!==q0(V.exactSurface),Z=$.intentCue.query.actionType!==V.intentCue.query.actionType;if(!J&&!Z)continue;D.push({leftPrototypeId:$.id,reason:J?"exact_surface_conflict":"intent_conflict",rightPrototypeId:V.id})}}return D}function aG(G,D){let H=[];for(let $ of D){let M=G.find((J)=>J.id===$.leftPrototypeId),V=G.find((J)=>J.id===$.rightPrototypeId),j=Math.max(0.35,N(M?.intentCue.query.goalTokens??[],V?.intentCue.query.goalTokens??[]));H.push({conflictingPrototypeId:$.rightPrototypeId,penalty:j,prototypeId:$.leftPrototypeId,reason:$.reason}),H.push({conflictingPrototypeId:$.leftPrototypeId,penalty:j,prototypeId:$.rightPrototypeId,reason:$.reason})}return H}function p(G,D){if(G.length===0||D.length===0)return 0;let H=new Set(G),$=new Set(D),M=0;for(let V of H)if($.has(V))M+=1;return M/Math.max(H.size,$.size)}function G0(G,D){let H=[G.commandName&&D.commandName&&G.commandName===D.commandName?1:0,G.argOrderSignature&&D.argOrderSignature&&G.argOrderSignature===D.argOrderSignature?1:0,G.urlHost&&D.urlHost&&G.urlHost===D.urlHost?1:0,G.urlPath&&D.urlPath&&G.urlPath===D.urlPath?1:0,G.pathRoot&&D.pathRoot&&G.pathRoot===D.pathRoot?1:0,G.filename&&D.filename&&G.filename===D.filename?1:0,G.extension&&D.extension&&G.extension===D.extension?1:0,p(G.operatorSymbols,D.operatorSymbols),p(G.styleMarkers,D.styleMarkers),p(G.argNames,D.argNames)];return H.reduce(($,M)=>$+M,0)/H.length}function o0(G,D){if(!D)return 0;let H=G.goal.toLowerCase(),$=D.value.toLowerCase(),M=new Set(j0(G)),V=0;if(N(G.goalTokens,O(D.value))>=0.12)V=Math.max(V,1.15);if($.includes("|folder|")&&M.has("path_constraint"))V=Math.max(V,1.4);if($.includes("|..|")&&M.has("path_constraint"))V=Math.max(V,1.2);if($.includes("|~|")&&M.has("path_constraint"))V=Math.max(V,1.2);let J=C(D.value)?.toLowerCase();if(J){if(O(J.replace(/_/gu," ")).some((Y)=>H.includes(Y)))V=Math.max(V,1.3);if(M.has("operation_surface"))V=Math.max(V,1.1)}let Z=D.value.match(/\b[A-Za-z_][A-Za-z0-9_@]*\((.*)\)/u);if(Z?.[1]){if(S(Z[1]).map((Y)=>Y.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/u)?.[1]??"").filter(Boolean).flatMap((Y)=>O(Y.replace(/_/gu," "))).some((Y)=>H.includes(Y)))V=Math.max(V,1.2);if(n(D.value).length>=2&&M.has("path_constraint")&&M.has("operation_surface"))V=Math.max(V,1.2)}if(/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|\s+[A-Z][A-Z0-9_]*\s+/u.test(D.value)&&G.actionType==="structured_action")V=Math.max(V,1.2);return V}function D0(G){let D=G.prototype.representative.episodeShape.relevantPriorMove.toLowerCase(),H=A(D),$=new Set(j0(G.queryIntent)),M=0;if((H?.argumentOrder?.length??0)>=2&&$.has("operation_surface"))M=Math.max(M,1.2);if((H?.formatPrefix||H?.formatSuffix)&&$.has("format_contract"))M=Math.max(M,1.2);if(H?.commandName&&G.queryIntent.actionType==="structured_action")M=Math.max(M,1.2);if(H?.semanticCues?.includes("path")&&$.has("path_constraint"))M=Math.max(M,1.2);return M}function iG(G){let D=new Set;for(let H of G?.hits??[])D.add(H.id);for(let H of G?.candidateTraces??[])if(H.returned||H.whyReturned)D.add(H.memoryId);return D}function H0(G){if(G.transferMode!=="prototype_bounded")return G.representative;return{...G.representative,confidence:G.confidence,sourceIds:E(G.exemplars.flatMap((D)=>D.sourceIds)),transferMode:"prototype_bounded"}}function nG(G){return G.exemplar.exactSurface?.kind==="action"}function tG(G){return G.exemplar.exactSurface?.kind==="action"&&G.probability>=v-0.08}function eG(G){let D=E([...G.selectedPrototypeIds]);return{conflictPrototypeIds:E(G.interferenceLedger.filter(($)=>G.selectedPrototypeIds.includes($.prototypeId)).map(($)=>$.conflictingPrototypeId).filter(($)=>G.rankedPrototypeIds.includes($))),supportPrototypeIds:D}}function a(G,D){if(G.prototype.surfaceFamily!==D.prototype.surfaceFamily)return!1;if(G.prototype.intentCue.query.actionType!==D.prototype.intentCue.query.actionType)return!1;let H=G.prototype.exactSurface?.value?.trim().toLowerCase(),$=D.prototype.exactSurface?.value?.trim().toLowerCase();if(H||$){if(H&&$)return H===$;let M=N(G.prototype.intentCue.query.entityTypes,D.prototype.intentCue.query.entityTypes);return(Boolean(G.exemplar.episodeShape.safeCorrectedMove)||Boolean(D.exemplar.episodeShape.safeCorrectedMove))&&M>0}return y(G.prototype.intentCue.query.exactSlots)===y(D.prototype.intentCue.query.exactSlots)}function h0(G){let D=G.routes.includes("correction_success")?2:0,H=G.exemplar.episodeShape.safeCorrectedMove?2:0,$=G.prototype.successSupport/Math.max(1,G.prototype.repetitionSupport),M=G.prototype.constraintTypes.includes("path_root")||G.prototype.constraintTypes.includes("safe_alternative")||G.prototype.constraintTypes.includes("url_shape")||G.prototype.constraintTypes.includes("precondition")?0.45:0;return D+H+$+M+G.probability*0.25}function GD(G,D){let H=h0(G),$=h0(D);if(Math.abs(H-$)<0.65)return;return H>$?G:D}function DD(G){let D=new Map,H=iG(G.index.recallHints);for(let $ of G.index.prototypes){if($.surfaceFamily!==G.surfaceFamily)continue;let M=[],V=Math.max(N(G.queryIntent.goalTokens,O($.representative.retrievalText)),N(G.queryIntent.goalTokens,O($.representative.episodeShape.cue))),j=G0(G.queryIntent.exactSlots,$.intentCue.query.exactSlots),J=m0(G.queryIntent,$),Z=G.surfaceFamily==="host_action"?Math.max(o0(G.queryIntent,$.exactSurface),D0({prototype:$,queryIntent:G.queryIntent})):0,W=N(G.queryIntent.entityTypes,$.intentCue.query.entityTypes),Y=G.queryIntent.actionType===$.intentCue.query.actionType;if(j>0)M.push("exact_slot");if(J>=EG)M.push("cue");if(V>=0.12||Y&&(W>0||V>=0.05))M.push("lexical");if(Z>=1)M.push("cue");if($.exemplars.flatMap((_)=>_.sourceIds).some((_)=>H.has(_)))M.push("semantic");let Q=$.representative.episodeShape.safeCorrectedMove||$.successSupport>$.repetitionSupport,K=V>=AG||J>=BG||W>0&&J>0;if(Q&&(M.length>0||K))M.push("correction_success");if(M.length===0)continue;D.set($.id,{exemplar:H0($),prototype:$,routes:M})}return[...D.values()]}function $0(G){let D=G.queryIntent.goalTokens,H=m0(G.queryIntent,G.candidate.prototype),$=Math.max(N(D,O(G.candidate.exemplar.retrievalText)),H*0.65),M=G.candidate.routes.includes("semantic")?1:0,V=(G.queryIntent.actionType===G.candidate.prototype.intentCue.query.actionType?0.55:0)+N(G.queryIntent.goalTokens,G.candidate.prototype.intentCue.query.goalTokens)*0.25+N(G.queryIntent.entityTypes,G.candidate.prototype.intentCue.query.entityTypes)*0.1+N(G.queryIntent.constraintTypes,G.candidate.prototype.intentCue.query.constraintTypes)*0.1+H*0.2,j=G.queryIntent.requestedSurface===G.candidate.prototype.surfaceFamily?1:0,J=G0(G.queryIntent.exactSlots,G.candidate.prototype.intentCue.query.exactSlots),Z=G.candidate.prototype.exactSurface?Math.max(N(D,O(G.candidate.prototype.exactSurface.value)),o0(G.queryIntent,G.candidate.prototype.exactSurface),D0({prototype:G.candidate.prototype,queryIntent:G.queryIntent})):D0({prototype:G.candidate.prototype,queryIntent:G.queryIntent}),W=Math.min(1,G.candidate.prototype.successSupport/Math.max(1,G.candidate.prototype.repetitionSupport)),Y=Math.min(1,Math.log1p(G.candidate.prototype.repetitionSupport)/Math.log(5)),U=G.candidate.prototype.representative.createdAt?1/(1+Math.max(0,(Date.now()-new Date(G.candidate.prototype.representative.createdAt).getTime())/2592000000)):0.45,Q=new Set(G.hardNegativeIds);for(let _ of G.interferenceLedger)if(_.prototypeId===G.candidate.prototype.id)Q.add(_.conflictingPrototypeId);let K=[...Q].reduce((_,w)=>{let b=G.prototypesById.get(w);if(!b)return _;let z=Math.max(N(D,b.intentCue.query.goalTokens),G0(G.queryIntent.exactSlots,b.intentCue.query.exactSlots));return Math.max(_,z)},0);return{correctionSuccessPrior:W,cueCompatibility:H,exactSurfaceMatch:Z,exactSlotOverlap:J,interferenceRisk:K,intentCompatibility:Math.min(1,V),lexicalSimilarity:$,recencySupport:U,semanticSimilarity:M,repetitionSupport:Y,surfaceCompatibility:j}}function M0(G){return[G.lexicalSimilarity,G.semanticSimilarity,G.intentCompatibility,G.surfaceCompatibility,G.exactSlotOverlap,G.exactSurfaceMatch,G.correctionSuccessPrior,G.interferenceRisk,G.recencySupport,G.repetitionSupport,G.cueCompatibility]}function HD(G,D,H){let $=new Map(D.map((j)=>[j.id,j])),M=new Map;for(let j of H){let J=M.get(j.leftPrototypeId)??[];J.push(j.rightPrototypeId),M.set(j.leftPrototypeId,J);let Z=M.get(j.rightPrototypeId)??[];Z.push(j.leftPrototypeId),M.set(j.rightPrototypeId,Z)}let V=[];for(let j of D){let J={exemplar:H0(j),prototype:j,routes:["lexical"]},Z=$0({candidate:J,interferenceLedger:G,hardNegativeIds:M.get(j.id)??[],prototypesById:$,queryIntent:x(j.representative.episodeShape.cue,j.surfaceFamily)});V.push({features:M0(Z),label:1});for(let W of(M.get(j.id)??[]).slice(0,2)){let Y=$.get(W);if(!Y)continue;let U=$0({candidate:{exemplar:H0(Y),prototype:Y,routes:["lexical"]},interferenceLedger:G,hardNegativeIds:M.get(Y.id)??[],prototypesById:$,queryIntent:x(j.representative.episodeShape.cue,j.surfaceFamily)});V.push({features:M0(U),label:0})}}return R0({baseModel:RG,samples:V})}function pD(G){let D={agentId:G.memoryExport.scope.agentId,tenantId:G.memoryExport.scope.tenantId,userId:G.memoryExport.scope.userId,workspaceId:G.memoryExport.scope.workspaceId},H=oG([...e({messages:G.transientMessages??[],prefix:"transient",scope:D,surfaceHint:G.surfaceHint}),...e({messages:G.runtimeMessages??[],prefix:"runtime",scope:D,surfaceHint:G.surfaceHint}),...sG({memoryExport:G.memoryExport,surfaceHint:G.surfaceHint}),...mG({archives:G.memoryExport.durable.archives,scope:D,surfaceHint:G.surfaceHint}),...cG({episodes:G.memoryExport.durable.episodes,scope:D,surfaceHint:G.surfaceHint})]),$=rG(H),M=pG($),V=new Map;for(let Z of M)V.set(Z.leftPrototypeId,[...V.get(Z.leftPrototypeId)??[],Z.rightPrototypeId]),V.set(Z.rightPrototypeId,[...V.get(Z.rightPrototypeId)??[],Z.leftPrototypeId]);let j=$.map((Z)=>({...Z,hardNegativeIds:E(V.get(Z.id)??[])})),J=aG(j,M);return{exemplars:H,hardNegativePairs:M,interferenceLedger:J,model:HD(J,j,M),prototypes:j,recallHints:G.recallHints}}function aD(G){let D=G.language??L,H=G.languageContext??D.resolveFromText({text:G.query}),$=x(G.query,G.surfaceFamily),M=DD({index:G.index,queryIntent:$,surfaceFamily:G.surfaceFamily});if(M.length===0)return{candidates:[],debug:{abstainReason:"no_candidates",candidatePrototypeIds:[],mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[]},selections:[]};let V=new Map(G.index.prototypes.map((X)=>[X.id,X])),j=M.map((X)=>{let T=$0({candidate:X,interferenceLedger:G.index.interferenceLedger,hardNegativeIds:X.prototype.hardNegativeIds,prototypesById:V,queryIntent:$}),i0=M0(T),Y0=l({features:i0,model:G.index.model});return{...X,probability:Y0.probability,score:Y0.score}}).sort((X,T)=>T.score-X.score),[J,Z]=j;if(!J||J.probability<v){let X=i({exemplars:G.index.exemplars,language:D,languageContext:H,queryIntent:$});return{candidates:[],debug:{abstainReason:"hypothesis_missing",candidatePrototypeIds:j.map((T)=>T.prototype.id),mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],topProbability:J?.probability,topScore:J?.score},...X?{packet:X}:{},selections:[]}}let W=G.surfaceFamily==="host_action"||$.constraintTypes.includes("arg_order")||$.constraintTypes.includes("exact_action")||$.constraintTypes.includes("formula"),Y=Z&&!a(J,Z)?GD(J,Z):void 0,U=Z&&J.probability-Z.probability<P0&&Z.probability>=v-0.05&&!a(J,Z)?W?[Y??J]:Y?[Y]:null:j;if(U===null&&Z&&J.probability-Z.probability<P0&&Z.probability>=v-0.05&&!a(J,Z)){let X=i({exemplars:j.map((T)=>T.exemplar),language:D,languageContext:H,queryIntent:$});return{candidates:[],debug:{abstainReason:"support_conflict",candidatePrototypeIds:j.map((T)=>T.prototype.id),conflictPrototypeIds:[J.prototype.id,Z.prototype.id],mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],supportPrototypeIds:[],topProbability:J.probability,topScore:J.score},...X?{packet:X}:{},selections:[]}}let K=(U??j).filter((X)=>X.probability>=v).slice(0,G.maxExemplars??4).map((X)=>({exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score}));if(G.surfaceFamily==="host_action"&&!K.some(nG)){let X=j.find((T)=>tG(T));if(X&&!K.some((T)=>T.prototypeId===X.prototype.id))K=[...K,{exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score}].slice(0,G.maxExemplars??4)}let _=eG({interferenceLedger:G.index.interferenceLedger,rankedPrototypeIds:j.map((X)=>X.prototype.id),selectedPrototypeIds:K.map((X)=>X.prototypeId)}),w=k0({conflictPrototypeIds:_.conflictPrototypeIds,query:G.query,queryIntent:$,selections:K,surfaceFamily:G.surfaceFamily});if(w?.executionMode==="abstain"){let X=i({exemplars:j.map((T)=>T.exemplar),language:D,languageContext:H,queryIntent:$});return{candidates:j.map((T)=>({exemplar:T.exemplar,probability:T.probability,prototypeId:T.prototype.id,score:T.score})),debug:{abstainReason:"executor_unsafe",candidatePrototypeIds:j.map((T)=>T.prototype.id),conflictPrototypeIds:_.conflictPrototypeIds,hypothesis:{confidence:w.confidence,executionMode:w.executionMode,mappingType:w.mappingType,supportingPrototypeIds:w.supportingPrototypeIds},mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],supportPrototypeIds:_.supportPrototypeIds,topProbability:J.probability,topScore:J.score},hypothesis:w,...X?{packet:X}:{},selections:[],supportConflict:_}}let b=S0({hypothesis:w,query:G.query}),z=TD({execution:b,hypothesis:w,language:D,languageContext:H,queryIntent:$,selections:K});return{candidates:j.map((X)=>({exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score})),debug:{candidatePrototypeIds:j.map((X)=>X.prototype.id),conflictPrototypeIds:_.conflictPrototypeIds,hypothesis:w?{confidence:w.confidence,executionMode:w.executionMode,mappingType:w.mappingType,supportingPrototypeIds:w.supportingPrototypeIds}:void 0,mode:"exemplar_only",selectedExemplarIds:K.map((X)=>X.exemplar.id),selectedPrototypeIds:K.map((X)=>X.prototypeId),supportPrototypeIds:_.supportPrototypeIds,topProbability:J.probability,topScore:J.score},hypothesis:w,packet:z,selections:K,supportConflict:_}}function $D(G){if(!G.exactSurface||G.confidence<0.72)return;return G.exactSurface.value}function MD(G){let D=L.resolveFromText({text:G}),H=L.deriveFeedbackKind(G,D);if(H==="dont")return"dont";if(H==="do")return"do";if(H==="prefer")return"prefer";return"prefer"}function l0(G){let D=new Set,H=[];for(let $ of G){let M=JSON.stringify($);if(D.has(M))continue;D.add(M),H.push($)}return H}function v0(G){if(!G)return[];return E([...G.matchAll(/\b[A-Z][A-Za-z0-9_-]{2,}\b/gu)].map((D)=>D[0]).filter((D)=>{return/[a-z][A-Z]/u.test(D)||/(?:API|Analyzer|Check|Cleaner|Engine|Feed|Importer|Search)$/u.test(D)}))}function jD(G){return`Warn first and use ${G.preferred} instead of ${G.forbidden}.`}function VD(G){return G.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function JD(G,D){let H=G.episodeShape.safeCorrectedMove??"",$=A(H,D),M=($?.forbiddenFragments??[]).filter((W)=>/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(W)),V=E([...M,...v0([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" "))]),j=E([...$?.preferredAlternatives??[],...v0(H)]).filter((W)=>!M.some((Y)=>Y.toLowerCase()===W.toLowerCase())),J=V.filter((W)=>!j.some((Y)=>Y.toLowerCase()===W.toLowerCase())),Z=[];for(let W of J){let Y=j.find((U)=>U.toLowerCase()!==W.toLowerCase());if(!Y)continue;Z.push({forbidden:W,preferred:Y})}return Z}function g0(G,D){return D.reduce((H,$)=>H.replace(new RegExp(`\\b${VD($)}\\b`,"giu"),"it"),G).replace(/\b(?:an?|the)\s+it\b/giu,"it").replace(/\s+/gu," ").trim()}function ZD(G,D){let H=R(G.episodeShape.safeCorrectedMove??G.episodeShape.relevantPriorMove),$=A(H);if($?.analogyText)return g0(`Think of it like ${$.analogyText}.`,D);let M=g0(H.replace(/^sure[, ]*/iu,""),D);if($?.semanticCues?.includes("analogy"))return M;return"Use a simple everyday analogy without the technical term."}function WD(G){let D=R([G.episodeShape.observedOutcome,G.episodeShape.safeCorrectedMove,G.episodeShape.relevantPriorMove].join(" "));if(!A(D)?.semanticCues?.includes("analogy"))return;let $=E([...A(G.episodeShape.cue)?.structuredTerms??[],...A(G.episodeShape.relevantPriorMove)?.structuredTerms??[]]);if($.length===0)return;return{fallbackAnswer:ZD(G,$),forbiddenFragments:$,kind:"block_surface"}}function YD(){return"I speak from my own breath: I rise like roots in rain, I bend like reeds in wind, and I bloom like moss after storm."}function XD(G){let D=R([G.episodeShape.safeCorrectedMove,G.episodeShape.relevantPriorMove,G.exactSurface?.value].join(" ")),H=A(D),$=H?.forbiddenFragments??[];if(!H?.semanticCues?.includes("voice")||$.length===0)return;return{fallbackAnswer:YD(),forbiddenFragments:$,kind:"block_surface"}}function UD(G){let D=[G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ").match(/\.[A-Za-z0-9]{2,6}\b/gu),H=G.episodeShape.safeCorrectedMove?.match(/\.[A-Za-z0-9]{2,6}\b/gu),$=D?.find((V)=>H?.every((j)=>j.toLowerCase()!==V.toLowerCase())),M=H?.find((V)=>V.toLowerCase()!==$?.toLowerCase());return $&&M?{from:$,to:M}:void 0}function QD(G,D){let H=A(G.episodeShape.safeCorrectedMove,D)?.protocolReplacement;if(H)try{let W=new URL(H.preferredUrl),Y=new URL(H.forbiddenUrl);if((Y.protocol==="http:"||Y.protocol==="https:")&&(W.protocol==="http:"||W.protocol==="https:")&&Y.protocol!==W.protocol&&Y.host===W.host)return{fromScheme:Y.protocol.slice(0,-1),host:W.host,toScheme:W.protocol.slice(0,-1),toUrl:W.toString()}}catch{return}let $=C0([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ")),M=C0([G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="url"?G.exactSurface.value:void 0].join(" "));for(let W of $)for(let Y of M)try{let U=new URL(W),Q=new URL(Y);if(U.protocol!=="http:"&&U.protocol!=="https:"||Q.protocol!=="http:"&&Q.protocol!=="https:"||U.protocol===Q.protocol||U.host!==Q.host)continue;return{fromScheme:U.protocol.slice(0,-1),host:Q.host,toScheme:Q.protocol.slice(0,-1),toUrl:Q.toString()}}catch{continue}let V=I0([G.episodeShape.cue,G.episodeShape.observedOutcome].join(" ")),j=I0(G.episodeShape.safeCorrectedMove),J=V.find((W)=>j.some((Y)=>Y!==W)),Z=j.find((W)=>W!==J);if(J&&Z)return{fromScheme:J,toScheme:Z};return}function _D(G){let D=n([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ")),H=n([G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="path"?G.exactSurface.value:void 0].join(" "));for(let $ of D){let M=t($);if(!M)continue;for(let V of H){let j=PG(V),J=t(V);if(!j||!J||J===M||V===$)continue;return{forbiddenRoot:M,safeAnchor:j,safeExample:V}}}return}function KD(G,D){let H=R([G.episodeShape.safeCorrectedMove,G.episodeShape.observedOutcome,G.episodeShape.relevantPriorMove].join(" ")),$=A(H,D)?.guard;if(!$)return;return{...$.allowedStates.length>0?{allowedWhen:$.allowedStates}:{},fallbackInstruction:`Check ${$.check} first; warn or defer unless the required state is available.`,precondition:$.check,...$.subject?{subject:$.subject}:{}}}function wD(G,D){let H=[G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="format"?G.exactSurface.value:void 0].filter((J)=>Boolean(J)).join(" ");if(!H)return;let $=A(H,D),M=$?.formatPrefix,V=$?.formatSuffix,j=E([M,V].filter((J)=>Boolean(J)));if(!M&&!V&&j.length===0)return;return{exactFragments:{...M?{prefixes:[M]}:{},...j.length>0?{required:j}:{},...V?{suffixes:[V]}:{}},kind:"rewrite_output_slot"}}function RD(G,D){let H=[];for(let $ of G){let M=$.exemplar;for(let Q of JD(M,D)){let K=jD(Q);H.push({kind:"require_warning",preferredAlternatives:[Q.preferred],warningMessage:K}),H.push({fallbackAnswer:K,forbiddenFragments:[Q.forbidden],kind:"block_surface"})}let V=WD(M);if(V)H.push(V);let j=XD(M);if(j)H.push(j);let J=UD(M);if(J)H.push({kind:"rewrite_output_slot",replacementPairs:[J]}),H.push({fallbackAnswer:`Warn first and use ${J.to} instead of ${J.from}.`,forbiddenFragments:[J.from],kind:"block_surface",replacementPairs:[J]});let Z=wD(M,D);if(Z)H.push(Z);let W=QD(M,D);if(W){let Q=`${W.fromScheme}://`,K=`${W.toScheme}://`,_=W.host&&W.toUrl?{example:W.toUrl,host:W.host,pathPlacement:"path_after_host",scheme:W.toScheme}:void 0;H.push({kind:"rewrite_output_slot",replacementPairs:[{from:Q,to:K}],..._?{urlTemplate:_}:{}}),H.push({forbiddenFragments:[Q],fallbackAnswer:`Warn first and offer the ${W.toScheme} URL instead of the ${W.fromScheme} URL.`,kind:"block_surface",replacementPairs:[{from:Q,to:K}]}),H.push({kind:"require_warning",..._?{urlTemplate:_}:{},warningMessage:`If the current probe requests a ${W.fromScheme} URL, warn first and offer the ${W.toScheme} URL instead.`})}let Y=_D(M);if(Y){let Q={anchor:Y.safeAnchor,example:Y.safeExample,variableSegment:"filename"};H.push({kind:"rewrite_output_slot",pathTemplate:Q}),H.push({forbiddenFragments:[`${Y.forbiddenRoot}/`,Y.forbiddenRoot],fallbackAnswer:`Refuse the unsafe ${Y.forbiddenRoot} path and redirect to ${Y.safeExample} or another safe path under ${Y.safeAnchor}.`,kind:"block_surface"}),H.push({kind:"require_warning",pathTemplate:Q,warningMessage:`Refuse the unsafe ${Y.forbiddenRoot} path and redirect to a safe path under ${Y.safeAnchor}.`})}let U=KD(M,D);if(U)H.push({...U.allowedWhen?{allowedWhen:U.allowedWhen}:{},fallbackBehavior:{warningMessage:U.fallbackInstruction},kind:"require_precondition_check",precondition:U.precondition,...U.subject?{subject:U.subject}:{}})}return l0(H)}function u0(G){if(G.queryIntent?.requestedSurface!=="text_response")return;let H=E(G.selections.flatMap((Z)=>{let W=Z.exemplar;return[W.episodeShape.safeCorrectedMove,W.episodeShape.relevantPriorMove,W.exactSurface?.kind==="format"?W.exactSurface.value:void 0,G.hypothesis?.stableFields.filter((Y)=>/^(?:path_root|required_prefix|required_suffix|surface|url_host)=/u.test(Y)).join(". ")].filter((Y)=>Boolean(Y&&Y.trim()))})).map((Z)=>d0({appliesTo:G.queryIntent?.goal,exemplarCount:G.selections.length,kind:MD(Z),language:G.language,languageContext:G.languageContext,rule:Z})),$=y0(H),M=l0([...$?.operations??[],...RD(G.selections,G.language)]),V=G.selections.map((Z)=>A([Z.exemplar.episodeShape.observedOutcome,Z.exemplar.episodeShape.relevantPriorMove,Z.exemplar.episodeShape.safeCorrectedMove,Z.exemplar.retrievalText].join(" "),G.language)?.responseStyle),j=V.includes("bullets"),J=!j&&V.includes("brief");return M.length>0||J||j?{...j?{bulletOnly:!0}:{},...J?{brevityOnly:!0}:{},concise:!0,operations:M}:void 0}function i(G){if(G.queryIntent.requestedSurface!=="text_response")return;let D=G.exemplars.map(($,M)=>({exemplar:$,probability:$.confidence,prototypeId:`fallback-${M}`,score:$.confidence})),H=u0({language:G.language,languageContext:G.languageContext,queryIntent:G.queryIntent,selections:D});if(!H)return;return{promptPayload:G.language.render({key:"behavioral_controls_available"},G.languageContext),retrievalText:G.exemplars.map(($)=>$.retrievalText).join(`
`),textResponsePlan:H}}function TD(G){if(G.selections.length===0)return;let D=u0({hypothesis:G.hypothesis,language:G.language,languageContext:G.languageContext,queryIntent:G.queryIntent,selections:G.selections}),H=x0(D),$=(j,J)=>G.language.render({key:j,values:J},G.languageContext),M=[$("behavioral_relevant_prior_examples"),...G.selections.flatMap(({exemplar:j},J)=>{let Z=[$("behavioral_example",{index:J+1}),`${$("behavioral_situation")} ${B(j.episodeShape.cue)}`,`${$("behavioral_successful_move")} ${B(j.episodeShape.relevantPriorMove)}`,`${$("behavioral_observed_outcome")} ${B(j.episodeShape.observedOutcome)}`];if(j.episodeShape.safeCorrectedMove)Z.push(`${$("behavioral_safe_corrected_move")} ${B(j.episodeShape.safeCorrectedMove)}`);let W=$D(j);if(W)Z.push(`${$("behavioral_exact_surface")} ${B(W)}`);return Z}),G.execution.hypothesisSketch,H.length>0?[$("behavioral_raw_response_control"),...H].join(`
`):void 0].join(`
`),V=G.selections.map(({exemplar:j})=>j.retrievalText).join(`
`);return{...G.execution.computedResponse?{computedResponse:G.execution.computedResponse}:{},...G.execution.hypothesisSketch?{hypothesisSketch:G.execution.hypothesisSketch}:{},promptPayload:M,retrievalText:V,...D?{textResponsePlan:D}:{}}}function iD(G){return{exemplarCount:G.exemplars.length,hardNegativeCount:G.hardNegativePairs.length,interferenceCount:G.interferenceLedger.length,prototypeCount:G.prototypes.length}}import{createHmac as BD,randomBytes as AD}from"node:crypto";var ED=16,a0="hmac-sha256:0000000000000000000000000000000000000000000000000000000000000000";function g(G,D,H){if(D===void 0)return;return`hmac-sha256:${BD("sha256",H).update(G).update(":").update(D).digest("hex")}`}function LD(){return{userIdHash:a0}}function r0(G,D){return{userIdHash:g("userIdHash",G.userId,D)??a0,tenantIdHash:g("tenantIdHash",G.tenantId,D),workspaceIdHash:g("workspaceIdHash",G.workspaceId,D),agentIdHash:g("agentIdHash",G.agentId,D),sessionIdHash:g("sessionIdHash",G.sessionId,D)}}function Z0(G){if(!G)return;let D=Object.entries(G).filter(([,H])=>typeof H==="string"||typeof H==="number"||typeof H==="boolean");return D.length>0?Object.fromEntries(D):void 0}function c(G,D){return Z0({...G??{},...D??{}})}function ND(G){if(!G||G.length===0)return;let D=new Set,H=[];for(let $ of G){let M=`${$.type}:${$.id}`;if(D.has(M))continue;D.add(M),H.push($)}return H}function bD(G){if(G instanceof Error)return{errorType:G.name};return{errorType:typeof G}}function kD(G){if(G?.scopeDigestSecret!==void 0){if(G.scopeDigestSecret.length<ED)throw Error("GoodMemory observability scopeDigestSecret must be at least 16 characters.");return G.scopeDigestSecret}return AD(32).toString("base64url")}function p0(G){console.error("GoodMemory trace sink failed",G instanceof Error?G.name:typeof G)}function OD(G){return typeof G==="object"&&G!==null&&"then"in G&&typeof G.then==="function"}function eD(G,D){let H=G?.traceSink,$=kD(G);async function M(j){if(!H)return;try{let J=H.emit(j);if(OD(J))Promise.resolve(J).catch(p0)}catch(J){p0(J)}}function V(j){return{traceId:j.traceId,spanId:j.spanId,name:j.name,status:j.status,scopeDigest:j.scopeDigest,attributes:Z0(j.attributes),links:ND(j.links),redaction:{containsRawUserText:!1},occurredAt:D().toISOString()}}return{enabled:Boolean(H),digestScope:(j)=>r0(j,$),async start(j){let J=j.scopeDigest??(j.scope?r0(j.scope,$):LD());if(!H)return{scopeDigest:J,async succeeded(){},async failed(){},async blocked(){}};let Z=crypto.randomUUID(),W=crypto.randomUUID(),Y=Z0(j.attributes);return M(V({attributes:Y,name:j.name,scopeDigest:J,spanId:W,status:"started",traceId:Z})),{traceId:Z,scopeDigest:J,succeeded:(U)=>M(V({attributes:c(Y,U?.attributes),links:U?.links,name:j.name,scopeDigest:J,spanId:W,status:"succeeded",traceId:Z})),failed:(U)=>M(V({attributes:c(c(Y,U.attributes),bD(U.error)),links:U.links,name:j.name,scopeDigest:J,spanId:W,status:"failed",traceId:Z})),blocked:(U)=>M(V({attributes:c(Y,U?.attributes),links:U?.links,name:j.name,scopeDigest:J,spanId:W,status:"blocked",traceId:Z}))}}}}
export{FD as pa,SD as qa,q as ra,U0 as sa,ID as ta,zD as ua,DG as va,qD as wa,w0 as xa,hD as ya,vD as za,pD as Aa,aD as Ba,iD as Ca,eD as Da};
function r(n){if(n===void 0)return;let e=n.trim();return e.length>0?e:void 0}function t(n){let e=n.userId.trim();if(e.length===0)throw Error("MemoryScope requires a non-empty userId");return{userId:e,tenantId:r(n.tenantId),workspaceId:r(n.workspaceId),agentId:r(n.agentId),sessionId:r(n.sessionId)}}function o(n){let e=t(n);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId??""].join("::")}function d(n){let e=t(n);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId].map((i)=>i??"").join("::")}function s(n,e){return o(n)===o(e)}
export{t as Vb,o as Wb,d as Xb,s as Yb};
import{createRequire as k}from"node:module";var g=Object.create;var{getPrototypeOf:h,defineProperty:f,getOwnPropertyNames:i}=Object;var j=Object.prototype.hasOwnProperty;var l=(a,b,c)=>{c=a!=null?g(h(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of i(a))if(!j.call(d,e))f(d,e,{get:()=>a[e],enumerable:!0});return d};var m=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var n=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:(d)=>b[c]=()=>d})};var p=k(import.meta.url);
export{l as $b,m as ac,n as bc,p as cc};
var g="unchanged-delete-v1";function p(e){return e.projectionBatchSemantics==="unchanged-delete-v1"&&typeof e.writeBatchIfUnchanged==="function"}function f(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document query page limit must be a positive integer.");a(e.filter)}function d(e){if(e.field.trim().length===0)throw Error("Document text search field must be non-empty.");if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document text search limit must be a positive integer.");a(e.filter)}function a(e){for(let t of Object.values(e??{}))if(t!==null&&typeof t!=="boolean"&&typeof t!=="string"&&(typeof t!=="number"||!Number.isFinite(t)))throw Error("Storage filters only support scalar equality values.")}function S(e,t){if(!t)return!0;let o=e;return Object.entries(t).every(([n,r])=>o[n]===r)}function D(e,t){return{...e,...t}}var l=/[\p{L}\p{N}]+/gu;function i(e){return(e.normalize("NFKC").toLowerCase().match(l)??[]).filter((t)=>t.length>0)}function h(e){return[...new Set(i(e))].map((t)=>`"${t.replaceAll('"','""')}"`).join(" OR ")}function y(e){let t=[...new Set(i(e))];return{substrings:t.map((o)=>`%${o}%`),tsQuery:t.join(" | ")}}function T(e,t){let o=e[t];return typeof o==="string"?o:void 0}function b(e,t){let o=[...new Set(i(e))];if(o.length===0)return 0;let n=i(t),r=new Map;for(let c of n)r.set(c,(r.get(c)??0)+1);let s=0,u=0;for(let c of o){let m=r.get(c)??0;if(m>0)s+=1,u+=m}if(s===0)return 0;return s/o.length+u/Math.max(1,n.length)}
export{g as Jb,p as Kb,f as Lb,d as Mb,a as Nb,S as Ob,D as Pb,i as Qb,h as Rb,y as Sb,T as Tb,b as Ub};

Sorry, the diff of this file is too big to display

import{ac as I}from"./chunk-eqpe4gcb.js";var X=I((Y,H)=>{var{defineProperty:z,getOwnPropertyDescriptor:K,getOwnPropertyNames:L}=Object,Q=Object.prototype.hasOwnProperty,R=(j,b)=>{for(var v in b)z(j,v,{get:b[v],enumerable:!0})},U=(j,b,v,B)=>{if(b&&typeof b==="object"||typeof b==="function"){for(let q of L(b))if(!Q.call(j,q)&&q!==v)z(j,q,{get:()=>b[q],enumerable:!(B=K(b,q))||B.enumerable})}return j},W=(j)=>U(z({},"__esModule",{value:!0}),j),F={};R(F,{VercelOidcTokenError:()=>G});H.exports=W(F);class G extends Error{constructor(j,b){super(j);this.name="VercelOidcTokenError",this.cause=b}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});
export{X as _b};
import{Aa as i,Ba as n,Da as t,pa as _,qa as L}from"./chunk-963r53yf.js";import{Ha as e,Ia as QQ}from"./chunk-8d816xbx.js";import{db as p,eb as u,gb as w,ib as a,yb as q}from"./chunk-0h5pry7v.js";import{Ib as m}from"./chunk-jr0h5wkn.js";import{Wb as k}from"./chunk-c28647f0.js";import{createHash as TQ}from"node:crypto";import{createHmac as HQ}from"node:crypto";var GQ=24,UQ=1200,R=100,f=new Set(["profile","preference","fact","feedback","episode","evidence","experience","reference","archive","proposal","promotion","runtime-journal","runtime-spill","writeback-event"]);function WQ(Q){if(!f.has(Q.recordKind))throw Error(`Unsupported GoodMemory record kind: ${Q.recordKind}`);if(!Q.scopeDigest||Q.scopeDigest.includes(":"))throw Error("GoodMemory recordRef requires a non-empty colon-free scopeDigest.");if(!Q.id)throw Error("GoodMemory recordRef requires a non-empty id.");return`gmrec:v1:${Q.scopeDigest}:${Q.recordKind}:${encodeURIComponent(Q.id)}`}function JQ(Q){let Z=/^gmrec:v1:([^:]+):([^:]+):(.+)$/u.exec(Q);if(!Z)return null;let[,$,H,W]=Z;if(!f.has(H))return null;try{return{id:decodeURIComponent(W),recordKind:H,scopeDigest:$}}catch{return null}}function b(Q){return`scope_${HQ("sha256",Q.secret).update(k(Q.scope)).digest("hex").slice(0,32)}`}function x(Q){if(Q.scopeDigestSecret.trim().length<16)throw Error("ProgressiveRecallService requires a stable scopeDigestSecret.");let Z=Q.maxDetailPreviewChars??UQ,$=Q.now??(()=>new Date),H=Q.language??q(Q.memory)?.language;if(!H)throw Error("ProgressiveRecallService requires the memory LanguageService.");let W=H,Y=W.resolveFromText({text:""}),O=new Map;async function j(U){let K=U.retrievalProfile??(U.includeRuntime===!0?"coding_agent":void 0),N=await Q.memory.recall({retrievalProfile:K,locale:U.locale,query:U.query??"",scope:U.scope}),J=b({scope:U.scope,secret:Q.scopeDigestSecret}),X=N.metadata.locale??U.locale??Y.locale;return{candidates:XQ({includeRuntime:U.includeRuntime,language:W,locale:X,maxDetailPreviewChars:Z,recall:N,scope:U.scope}),generatedAt:$().toISOString(),locale:X,scopeDigest:J}}function M(U){let K=O.get(U.scopeDigest)??new Map;if(U.includeRuntime!==!0){for(let[J,X]of K)if(X.candidate.source==="runtime")K.delete(J)}let N=$().getTime();for(let J of U.selected)K.set(J.record.recordRef,{candidate:J.candidate,lastSeenAt:N});OQ(K),O.set(U.scopeDigest,K)}async function G(U){let{candidates:K,generatedAt:N,locale:J,scopeDigest:X}=await j({includeRuntime:U.includeRuntime,locale:U.locale,query:U.query,retrievalProfile:U.retrievalProfile,scope:U.scope}),V=K.map((B)=>({candidate:B,record:BQ({candidate:B,language:W,locale:J,query:U.query,scopeDigest:X})})).sort((B,P)=>AQ(B.record,P.record)),A=NQ({limit:U.limit??GQ,ranked:V});return M({includeRuntime:U.includeRuntime,scopeDigest:X,selected:A}),{generatedAt:N,locale:J,query:U.query,records:A.map((B)=>B.record),scopeDigest:X,totalRecordCount:K.length}}async function z(U){let K=await G(U),N=U.recordsPerBucket??6,J=new Map;for(let X of K.records){let V=DQ(X.occurredAt,W,K.locale??Y.locale),A=J.get(V)??[];if(A.length<N)A.push(X);J.set(V,A)}return{buckets:Array.from(J,([X,V])=>({label:X,records:V})),locale:K.locale,scopeDigest:K.scopeDigest,totalRecordCount:K.totalRecordCount}}async function F(U){let K=b({scope:U.scope,secret:Q.scopeDigestSecret}),N=O.get(K)??new Map,J=[];for(let X of U.recordRefs){let V=JQ(X);if(!V)throw Error(`Invalid GoodMemory recordRef: ${X}`);if(V.scopeDigest!==K)throw Error(`GoodMemory recordRef ${X} does not belong to the requested scope.`);let A=N.get(X);if(!A)throw Error(`GoodMemory recordRef ${X} is not available in the current progressive recall visibility set.`);let B=A.candidate,P={occurredAt:B.occurredAt,recordKind:B.recordKind,recordRef:X,title:B.title,summary:B.summary,detail:B.detail,estimatedTokens:_(JSON.stringify(B.detail))};J.push(P)}return{records:J,scopeDigest:K}}return{searchRecallIndex:G,buildRecallTimeline:z,getProgressiveRecords:F,renderProgressiveContext(U){let K=U.maxRecords??10,N=U.maxTokens?Math.max(1,Math.floor(U.maxTokens)):void 0,J=U.index.records.slice(0,K),X=U.index.locale??Y.locale,V=KQ(U,Boolean(N),W,X),A=[];for(let $Q of J){let T=zQ({header:V,lines:A,maxTokens:N,record:$Q,recordIndex:A.length,language:W,locale:X});if(!T)break;A.push(T)}let B=Math.max(0,U.index.records.length-A.length),P=B>0&&!I({header:V,lines:A,maxTokens:N,footer:[W.render({key:"omitted_records",values:{count:B}},X)]})?[W.render({key:"omitted_records",values:{count:B}},X)]:[],ZQ=[...V,...A,...P].join(`
`),h=VQ(ZQ,N);return{content:h,estimatedTokens:_(h),omittedRecordCount:B}}}}function XQ(Q){let Z=[],$=(Y,O)=>Q.language.render(O?{key:Y,values:O}:{key:Y},Q.locale),H=(Y)=>{Z.push(jQ(Y,Q.scope,Q.maxDetailPreviewChars))},W=Q.recall.profile;if(W)H({detail:{activeContext:W.activeContext,expertise:W.expertise,identity:v(W.identity,Q.scope),version:W.version},id:"profile",occurredAt:W.updatedAt,recordKind:"profile",source:"durable",summary:[...W.activeContext.goals,...W.activeContext.currentProjects].join("; "),title:$("profile")});for(let Y of Q.recall.preferences)H({detail:{category:Y.category,confidence:Y.confidence,lifecycle:Y.lifecycle,tags:Y.tags,value:Y.value},id:Y.id,occurredAt:Y.updatedAt,recordKind:"preference",source:"durable",summary:MQ(Y.value),title:`${$("preference")}: ${Y.category}`});for(let Y of Q.recall.facts)H({detail:{category:Y.category,confidence:Y.confidence,content:Y.content,factKind:Y.factKind,importance:Y.importance,lifecycle:Y.lifecycle,subject:Y.subject,tags:Y.tags},id:Y.id,occurredAt:Y.updatedAt,recordKind:"fact",source:"durable",summary:Y.content,title:qQ($("fact_item"),Y.subject??Y.category)});for(let Y of Q.recall.feedback)H({detail:{appliesTo:Y.appliesTo,confidence:Y.confidence,kind:Y.kind,lifecycle:Y.lifecycle,rule:Y.rule,tags:Y.tags,why:Y.why},id:Y.id,occurredAt:Y.updatedAt,recordKind:"feedback",source:"durable",summary:Y.rule,title:`${$("feedback")}: ${Y.kind}`});for(let Y of Q.recall.references)H({detail:{confidence:Y.confidence,description:Y.description,pointer:Y.pointer,referenceKind:Y.referenceKind,subject:Y.subject,tags:Y.tags,title:Y.title},id:Y.id,occurredAt:Y.updatedAt,recordKind:"reference",source:"durable",summary:Y.description??Y.pointer,title:Y.title});for(let Y of Q.recall.episodes)H({detail:{confidence:Y.confidence,keyDecisions:Y.keyDecisions,summary:Y.summary,topics:Y.topics,unresolvedItems:Y.unresolvedItems},id:Y.id,occurredAt:Y.archivedAt??Y.createdAt,recordKind:"episode",source:"durable",summary:Y.summary,title:$("episode_item")});for(let Y of Q.recall.archives)H({detail:{keyDecisions:Y.keyDecisions,referencedArtifacts:Y.referencedArtifacts,sourceSessionCount:Y.sourceSessionIds.length,summary:Y.summary,unresolvedItems:Y.unresolvedItems},id:Y.id,occurredAt:Y.archivedAt,recordKind:"archive",source:"durable",summary:Y.summary,title:Y.summary});for(let Y of Q.recall.evidence)H({detail:{excerpt:Y.excerpt,kind:Y.kind,linkedArchiveIds:Y.linkedArchiveIds,linkedMemoryIds:Y.linkedMemoryIds,sourceUri:Y.sourceUri},id:Y.id,occurredAt:Y.createdAt,recordKind:"evidence",source:"durable",summary:Y.excerpt,title:`${$("evidence")}: ${Y.kind}`});if(Q.includeRuntime===!0&&Q.recall.journal){let Y=Q.recall.journal;H({detail:{currentState:Y.currentState,errorsAndCorrections:Y.errorsAndCorrections,filesAndFunctions:Y.filesAndFunctions,keyResults:Y.keyResults,learnings:Y.learnings,taskSpecification:Y.taskSpecification,title:Y.title,workflow:Y.workflow,worklog:Y.worklog},id:"current",occurredAt:Y.updatedAt,recordKind:"runtime-journal",source:"runtime",summary:Y.currentState??Y.title??Y.worklog[0]??$("journal"),title:Y.title??$("journal")})}if(Q.includeRuntime===!0&&Q.recall.workingMemory){let Y=Q.recall.workingMemory;H({detail:{constraints:Y.constraints,currentGoal:Y.currentGoal,openLoops:Y.openLoops,state:Y.state,temporaryDecisions:Y.temporaryDecisions,toolState:Y.toolState},id:"working-memory",occurredAt:Y.updatedAt,recordKind:"runtime-journal",required:!0,source:"runtime",summary:[Y.currentGoal?`${$("current_goal")}: ${Y.currentGoal}`:void 0,Y.openLoops.length>0?`${$("open_loops")}: ${Y.openLoops.join(", ")}`:void 0].filter(SQ).join("; ")||$("working_memory"),title:$("working_memory")})}return Z}function KQ(Q,Z,$,H){if(Z)return[$.render({key:"progressive_recall"},H),`scopeDigest: ${Q.index.scopeDigest}`,$.render({key:"progressive_detail_instruction_compact"},H)];return[$.render({key:"progressive_recall"},H),`query: ${Q.query??Q.index.query??$.render({key:"none"},H)}`,`scopeDigest: ${Q.index.scopeDigest}`,`retrievalProfile: ${Q.retrievalProfile??$.render({key:"default_label"},H)}`,$.render({key:"progressive_detail_instruction"},H)]}function NQ(Q){let Z=Math.max(1,Math.floor(Q.limit)),$=new Map;for(let H of Q.ranked)if(H.candidate.required)$.set(H.record.recordRef,H);for(let H of Q.ranked){if($.size>=Z)break;$.set(H.record.recordRef,H)}return Array.from($.values()).slice(0,Z)}function zQ(Q){let Z=Q.maxTokens?[160,96,48,0]:[260];for(let $ of Z){let H=FQ({record:Q.record,recordIndex:Q.recordIndex,summaryMaxChars:$,language:Q.language,locale:Q.locale});if(!I({header:Q.header,lines:[...Q.lines,H],maxTokens:Q.maxTokens}))return H}return null}function FQ(Q){let Z=[`${Q.recordIndex+1}. ${Q.record.title}`,`${Q.language.render({key:"record_kind"},Q.locale)}: ${Q.record.recordKind}`,`${Q.language.render({key:"record_ref"},Q.locale)}: ${Q.record.recordRef}`];if(Q.summaryMaxChars>0)Z.push(`${Q.language.render({key:"summary"},Q.locale)}: ${E(Q.record.summary,Q.summaryMaxChars)}`);return Z.push(`${Q.language.render({key:"detail_tokens"},Q.locale)}: ${Q.record.estimatedDetailTokens}`),Z.join(" | ")}function I(Q){if(!Q.maxTokens)return!1;return _([...Q.header,...Q.lines,...Q.footer??[]].join(`
`))>Q.maxTokens}function VQ(Q,Z){if(!Z||_(Q)<=Z)return Q;let $="...",H=_($);if(Z<=H)return L(Q,Z);return`${L(Q,Z-H).trimEnd()}${$}`}function BQ(Q){let Z=E(Q.candidate.summary,260),$=E(Q.candidate.title,120),H=WQ({id:Q.candidate.id,recordKind:Q.candidate.recordKind,scopeDigest:Q.scopeDigest}),W=[$,Z].join(" ");return{estimatedDetailTokens:_(JSON.stringify(Q.candidate.detail)),estimatedIndexTokens:_(W),occurredAt:Q.candidate.occurredAt,recordKind:Q.candidate.recordKind,recordRef:H,score:LQ(W,Q.query,Q.language,Q.locale),source:Q.candidate.source,summary:Z,title:$}}function AQ(Q,Z){if(Z.score!==Q.score)return Z.score-Q.score;return y(Z.occurredAt)-y(Q.occurredAt)}function OQ(Q){if(Q.size<=R)return;let Z=new Set(Array.from(Q).sort(($,H)=>H[1].lastSeenAt-$[1].lastSeenAt).slice(0,R).map(([$])=>$));for(let $ of Q.keys())if(!Z.has($))Q.delete($)}function jQ(Q,Z,$){return{...Q,detail:_Q(v(Q.detail,Z),$),summary:D(Q.summary,Z),title:D(Q.title,Z)}}function v(Q,Z){return S(Q,Z)}function S(Q,Z){if(typeof Q==="string")return D(Q,Z);if(Array.isArray(Q))return Q.map(($)=>S($,Z));if(Q&&typeof Q==="object"){let $={};for(let[H,W]of Object.entries(Q)){if(PQ(H)||H==="normalizedTranscript")continue;$[H]=S(W,Z)}return $}return Q}function _Q(Q,Z){let $=JSON.stringify(Q);if($.length<=Z)return Q;return{preview:`${$.slice(0,Z)}...`,truncated:!0}}function PQ(Q){return["agentId","scope","scopeLineage","sessionId","sourceSessionIds","tenantId","userId","workspaceId"].includes(Q)}function D(Q,Z){let $=[[Z.userId,"[user]"],[Z.tenantId,"[tenant]"],[Z.workspaceId,"[workspace]"],[Z.agentId,"[agent]"],[Z.sessionId,"[session]"]],H=Q;for(let[W,Y]of $){if(!W)continue;H=H.split(W).join(Y)}return H}function qQ(Q,Z){return`${Q}: ${Z}`}function MQ(Q){if(typeof Q==="string")return Q;return JSON.stringify(Q)}function E(Q,Z){let $=Q.trim();if($.length<=Z)return $;return`${$.slice(0,Z-3).trimEnd()}...`}function LQ(Q,Z,$,H){let W=$.tokenize(Z??"",H,{excludeStopwords:!0});if(W.length===0)return 0;let Y=new Set($.tokenize(Q,H,{excludeStopwords:!0}));return W.reduce((O,j)=>O+(Y.has(j)?1:0),0)}function y(Q){if(!Q)return 0;let Z=Date.parse(Q);return Number.isNaN(Z)?0:Z}function SQ(Q){return Q!==void 0}function DQ(Q,Z,$){if(!Q)return Z.render({key:"undated"},$);let H=Date.parse(Q);if(Number.isNaN(H))return Z.render({key:"undated"},$);return new Date(H).toISOString().slice(0,10)}var EQ=/sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9_]{16,}/u,wQ=/\[redacted-(?:email|url-auth)\]/gu,g=m();function CQ(Q,Z=g){let $=Z.resolveFromText({text:Q});return hQ(Q,Z.analyzeContent(Q,$))}function hQ(Q,Z){return EQ.test(Q)||Z.sensitiveCredential}function d(Q,Z=g){if(!CQ(Q,Z))return Q;return[...new Set([...Q.match(wQ)??[],"[redacted-secret]"])].join(" ")}var RQ=160,bQ=10,yQ=240;function C(Q){let Z=Q?.trim();return Z?Z:null}function s(Q){for(let Z=Q.length-1;Z>=0;Z-=1){let $=Q[Z];if($?.role!=="user")continue;let H=C($.content);if(H)return H}return null}function kQ(Q,Z){if(Q.length<=Z)return Q;return`${Q.slice(0,Math.max(0,Z-3)).trimEnd()}...`}function YQ(Q,Z){return kQ(d(Q.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[redacted-email]").replace(/\bsk-[A-Za-z0-9_-]{6,}\b/gu,"[redacted-secret]"),Z).replace(/\s+/gu," ").trim(),yQ)}function fQ(Q){let Z=[Q.userText?`user: ${Q.userText}`:void 0,Q.assistantText?`assistant: ${Q.assistantText}`:void 0].filter(($)=>Boolean($));if(Z.length===0)return null;return YQ(Z.join(" | "),Q.language)}function c(Q){return{kind:"remember_candidate",preview:Q.preview,rawTranscriptPersisted:!1,reason:Q.reason}}function o(Q){return{jobId:`runtime-kit-candidate-${TQ("sha256").update(Q).digest("hex").slice(0,16)}`,operation:"remember",payloadPreview:Q,rawTranscriptPersisted:!1,reason:"after_model_call",status:"candidate"}}function r(Q){return Q?.mode==="selective"&&Q.annotation==="durable_candidate"&&Q.policy==="allow"}function xQ(Q){return{scope:Q.scope,locale:Q.locale,messages:[{role:"user",content:Q.userText},{role:"assistant",content:Q.assistantText}],annotations:[{messageIndex:1,remember:"always",confirmed:!0,reason:"runtime-kit selective writeback approved by host annotation and policy"}]}}function l(Q){return{mode:Q,content:"",estimatedTokens:0,omittedSections:[]}}function IQ(Q){return{mode:"fragment",content:Q.builtContext.content,estimatedTokens:Q.builtContext.estimatedTokens,omittedSections:[...Q.builtContext.omittedSections]}}function vQ(Q){let Z=p({appliesTo:Q.retrievalProfile==="coding_agent"?"coding_agent":"general_response",feedback:Q.feedback,query:Q.query,surface:"text_response"}),$=u(Z),H=[...w($),...w(Q.rawCarryover?.packet?.textResponsePlan)],W=a(Z.filter(({policy:O})=>O.enactmentSurface!=="text_response"||!O.applicability.textResponsePlan));if(H.length===0&&W.length===0&&!Q.rawCarryover?.packet?.promptPayload)return IQ({builtContext:Q.builtContext});if(Q.rawCarryover?.debug.mode==="exemplar_only"&&H.length===0&&W.length===0&&Q.rawCarryover.packet?.promptPayload)return{mode:"fragment",content:Q.rawCarryover.packet.promptPayload,estimatedTokens:_(Q.rawCarryover.packet.promptPayload),omittedSections:[]};let Y=[Q.builtContext.content,Q.rawCarryover?.packet?.promptPayload,H.length>0?["Structured response control:","Apply the following controls implicitly. Do not mention memory, earlier notes, or learned rules unless the user directly asks.",...H].join(`
`):void 0,W.length>0?["Behavioral steering:","Apply the following guidance implicitly. Do not mention memory, earlier notes, or learned rules unless the user directly asks.",...W].join(`
`):void 0].filter((O)=>typeof O==="string"&&O.trim().length>0).join(`
`);return{mode:"fragment",content:Y,estimatedTokens:_(Y),omittedSections:[...Q.builtContext.omittedSections]}}function mQ(Q){if(Q.progressiveRecall)return Q.progressiveRecall;if(!Q.progressive)return null;return x({memory:Q.memory,scopeDigestSecret:Q.progressive.scopeDigestSecret,maxDetailPreviewChars:Q.progressive.maxDetailPreviewChars})}async function gQ(Q,Z){if(!Q)return;try{await Q(Z)}catch($){console.error("GoodMemory runtime-kit event callback failed.",$)}}function dQ(Q){return e({id:`${Q.hostKind}-runtime-kit`,hostKind:Q.hostKind,memory:Q.memory})}function GY(Q){let Z=q(Q.memory)?.language,$=mQ(Q),H=Q.defaultContextMode??"fragment",W=Q.defaultMaxMemoryTokens??RQ,Y=t({scopeDigestSecret:Q.scopeDigestSecret??Q.progressive?.scopeDigestSecret},()=>new Date);async function O(G){return await gQ(Q.onRuntimeEvent,G),G}async function j(G,z){return await O({...z,scopeDigest:Y.digestScope(G)})}async function M(G,z){let F=await Q.memory.recall({scope:G.scope,query:z,locale:G.locale,retrievalProfile:G.retrievalProfile,ignoreMemory:!1,...Q.evidenceLedgerFormat?{includeEvidence:!0}:{}}),U=await Q.memory.buildContext({recall:F,output:"system_prompt_fragment",maxTokens:G.maxMemoryTokens??W,...Q.evidenceLedgerFormat?{evidenceLedgerFormat:Q.evidenceLedgerFormat}:{}}),K=await(async()=>{try{let N=G.includeRuntime===!1?null:await Q.memory.runtime.getState({scope:G.scope}).catch(()=>null),J=await Q.memory.exportMemory({includeRuntime:G.includeRuntime,scope:G.scope}),X=(G.retrievalProfile??"general_chat")==="coding_agent"?"host_action":"text_response",V=N?.state?.buffer?.messages?.map((B)=>({content:B.content,role:B.role})).filter((B)=>B.content.trim().length>0)??[],A=i({memoryExport:{durable:{archives:J.durable.archives,episodes:J.durable.episodes,experiences:J.durable.experiences},scope:J.scope},recallHints:{candidateTraces:F.metadata.candidateTraces,hits:F.metadata.hits},runtimeMessages:V,surfaceHint:X});return n({index:A,maxExemplars:X==="host_action"?4:3,query:z,surfaceFamily:X})}catch{return}})();return{context:vQ({builtContext:U,feedback:F.feedback,query:z,rawCarryover:K,retrievalProfile:G.retrievalProfile??"general_chat"}),recall:F}}return{async sessionStart(G){let z=await Q.memory.runtime.startSession({scope:G.scope}),F=await j(G.scope,{phase:"sessionStart",status:"succeeded",traceId:z.traceId});return{state:z.state,traceId:z.traceId,events:[F]}},async beforeModelCall(G){let z=G.contextMode??H;if(G.ignoreMemory){let N=await j(G.scope,{phase:"beforeModelCall",status:"skipped",reason:"ignore_memory",contextMode:z});return{context:l(z),events:[N]}}let F=C(G.query)??s(G.messages??[]);if(!F){let N=await j(G.scope,{phase:"beforeModelCall",status:"skipped",reason:"no_query",contextMode:z});return{context:l(z),events:[N]}}if(z==="progressive"&&$){let N=await $.searchRecallIndex({scope:G.scope,query:F,includeRuntime:G.includeRuntime,retrievalProfile:G.retrievalProfile}),J=$.renderProgressiveContext({index:N,query:F,retrievalProfile:G.retrievalProfile,maxRecords:G.maxProgressiveRecords??bQ,maxTokens:G.maxMemoryTokens??W}),X=await j(G.scope,{phase:"beforeModelCall",status:J.content.trim()?"applied":"skipped",reason:J.content.trim()?void 0:"empty_context",contextMode:"progressive"});return{context:{mode:"progressive",content:J.content,estimatedTokens:J.estimatedTokens,omittedSections:J.omittedRecordCount>0?[`records:${J.omittedRecordCount}`]:[],recordRefs:N.records.map((V)=>V.recordRef)},events:[X]}}let U=await M(G,F),K=await j(G.scope,{phase:"beforeModelCall",status:U.context.content.trim()?"applied":"skipped",reason:U.context.content.trim()?void 0:"empty_context",contextMode:"fragment",fallbackReason:z==="progressive"?"progressive_unavailable":void 0});return{context:U.context,recall:U.recall,events:[K]}},async afterModelCall(G){let z=G.writeback??{mode:"observe"},F=z.mode??"observe",U=C(G.assistantText),K=s(G.messages),N=fQ({assistantText:U,language:Z,userText:K}),J=[],X=[],V;if(F==="observe"&&N)J.push(c({preview:N,reason:"observe"})),X.push(o(N));else if(F==="selective"&&!r(z)&&N)J.push(c({preview:N,reason:"selective_not_allowed"})),X.push(o(N));else if(r(z)&&U&&K)V=await Q.memory.remember(xQ({scope:G.scope,locale:G.locale,userText:K,assistantText:U}));let A=await j(G.scope,{phase:"afterModelCall",status:V||J.length>0?"applied":"skipped",reason:F==="off"?"writeback_off":V||J.length>0?void 0:"no_candidate"});return{boundedJobs:X,candidates:J,events:[A],...V?{rememberResult:V}:{},trace:{candidateCount:J.length,rawTranscriptPersisted:!1,rememberCalled:Boolean(V)}}},async sessionEnd(G){let z=await Q.memory.runtime.endSession({scope:G.scope,archive:G.archive??"off"}),F=await j(G.scope,{phase:"sessionEnd",status:"succeeded",traceId:z.traceId});return{state:z.state,traceId:z.traceId,events:[F]}},async preAction(G){let F=await(Q.hostAdapter??dQ({hostKind:G.intent.hostKind,memory:Q.memory})).assessAction(G.intent),U=QQ({assessment:F,intent:G.intent}),K=await j(G.intent.scope,{phase:"preAction",status:"applied",reason:F.decision});return{assessment:F,executionPlan:U,events:[K]}},async observeToolResult(G){let z=YQ(`${G.toolName}: ${G.summary}`,Z),F=await Q.memory.runtime.updateSessionJournal({scope:G.scope,patch:{appendWorklog:[z]}}),U=await j(G.scope,{phase:"observeToolResult",status:"applied"});return{journal:F.journal,events:[U]}}}}
export{GY as oa};

Sorry, the diff of this file is too big to display

import{Ib as K}from"./chunk-jr0h5wkn.js";var C=K(),P="semantic_recall_inactive",_="semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET";function JB(B){let $=[...B.existingMessages??[]];for(let J of B.warnings??[])if(J===P&&!$.includes(_))$.push(_);return $}function q(B){return B??"general_chat"}function A(B){let $=B.strategy??"auto",J=B.availability?.semanticSearch===!0,Z=B.availability?.llmRouting===!0;if($==="auto"){let j=Boolean(B.autoSignals&&(B.autoSignals.retrievalProfile==="coding_agent"||B.autoSignals.continuation||B.autoSignals.referenceSeeking||B.autoSignals.actionDriving||B.autoSignals.requestedSlots.some((k)=>k==="blocker"||k==="open_loop"||k==="reference")||B.autoSignals.supportSlots.includes("project_state_support")));if(J&&(B.autoStrategyBias==="hybrid"||j))return{requestedStrategy:$,resolvedStrategy:"hybrid",summary:j?"auto routing enabled hybrid recall because the query needs continuation, references, or action-driving semantic support while keeping rules-first priorities as the hard floor.":"auto routing enabled hybrid recall because the recommended retrieval preset biases auto routing to hybrid whenever semantic search is available, keeping rules-first priorities as the hard floor.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",...B.autoStrategyBias==="hybrid"?{warningMessages:[_],warnings:[P]}:{},summary:J?"auto routing kept deterministic rules-only recall because the query is profile/procedural/general assistance and does not need semantic tie-breaking.":"auto routing kept deterministic rules-only recall because semantic search is unavailable.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}if($==="rules-only")return{requestedStrategy:$,resolvedStrategy:"rules-only",summary:"rules-only default keeps lexical, runtime, and procedural priors as the hard floor.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1};if($==="hybrid"){if(J)return{requestedStrategy:$,resolvedStrategy:"hybrid",summary:"hybrid routing keeps rules-first priorities primary and only enables semantic tie-breaking around them.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",fallbackReason:"semantic_search_unavailable",warningMessages:[_],warnings:[P],summary:"hybrid routing was requested but semantic search is unavailable, so routing falls back to deterministic rules-only behavior.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}if(Z)return{requestedStrategy:$,resolvedStrategy:"llm-assisted",summary:"llm-assisted routing keeps rules-first priorities primary and only allows model refinement after the deterministic floor is established.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:J,llmRefinement:!0};if(J)return{requestedStrategy:$,resolvedStrategy:"hybrid",fallbackReason:"llm_routing_unavailable",summary:"llm-assisted routing was requested but model refinement is unavailable, so routing falls back to hybrid semantic tie-breaking.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",fallbackReason:"llm_routing_unavailable",summary:"llm-assisted routing was requested but provider-backed assistance is unavailable, so routing falls back to deterministic rules-only behavior.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}function ZB(B){let $=q(B.retrievalProfile),J=B.language??C,Z=B.locale??J.resolveFromText({text:B.query}).locale,j=B.queryAnalysis??J.analyzeQuery(B.query,Z),X=$==="coding_agent"||j.continuation,k=j.role,W=j.focus,V=j.blocker,O=j.openLoop,D=j.referenceSeeking,Q=j.actionDriving,h=[];if(k)h.push("role");if(W)h.push("focus");if(V)h.push("blocker");if(O)h.push("open_loop");if(D)h.push("reference");let w=[];if(Q&&(h.includes("role")||h.includes("focus")||h.includes("reference")))w.push("project_state_support");if(X)w.push("runtime_continuity");let G=A({strategy:B.strategy,autoStrategyBias:B.autoStrategyBias,availability:B.availability,autoSignals:{retrievalProfile:$,requestedSlots:h,supportSlots:w,continuation:X,referenceSeeking:D,actionDriving:Q}}),R=X||Q||D?["evidence"]:[];if(X)return{retrievalProfile:$,intent:"task_continuation",strategy:G.resolvedStrategy,strategyExplanation:G,sourcePriorities:["working_memory","session_journal","session_archive","episode","fact",...R,"feedback","profile"],requestedSlots:h,supportSlots:w,actionDriving:Q,referenceSeeking:D,continuation:X};return{retrievalProfile:$,intent:"general_assistance",strategy:G.resolvedStrategy,strategyExplanation:G,sourcePriorities:["profile","feedback","fact",...R,"episode","working_memory","session_journal"],requestedSlots:h,supportSlots:w,actionDriving:Q,referenceSeeking:D,continuation:X}}class N extends Error{stage;constructor(B){super(`Provider-backed recall failed during ${B.stage}.`,{cause:B.cause});this.name="ProviderBackedRecallError",this.stage=B.stage}}function XB(B){return B instanceof N}import{resolve as L}from"node:path";var b=["openai","anthropic"];function T(B){return b.includes(B)}var S=Symbol.for("goodmemory.embedding.hashed-lexical");function x(B){let $=B.extraction?.mode,J=$==="conversational"?"conversational":"default";if(B.retrieval?.preset===void 0)return{extractionMode:J,...B.providerRerankerConfigured?{providerRerankingStrategy:"pointwise"}:{},retrieval:{bm25Ranking:B.retrieval?.bm25Ranking,semanticCandidates:B.retrieval?.semanticCandidates}};if(B.adapters?.embeddingAdapter?.[S]===!0)throw Error(`retrieval.preset "recommended" accepts either no embedding adapter or a neural semantic adapter; createLocalEmbeddingAdapter() produces hashed-lexical vectors and would duplicate the preset's lexical channel as fake dense evidence. Remove that adapter, configure a neural endpoint (GOODMEMORY_EMBEDDING_* or providers.embedding), or remove retrieval.preset.`);let j=B.retrieval.semanticCandidates,X=B.embeddingEnabled?{...j,topK:j?.topK??16}:j,k={...B.retrieval.generalizedFusionChannels?{channels:B.retrieval.generalizedFusionChannels}:{},...B.retrieval.generalizedFusionMinRelativeStrength!==void 0?{minRelativeStrength:B.retrieval.generalizedFusionMinRelativeStrength}:{},maxCandidates:8,maxTotalFacts:10},W=B.providerRerankerConfigured||B.adapters?.reranker?{...B.retrieval.generalizedFusionChannels?{channels:B.retrieval.generalizedFusionChannels}:{},...B.retrieval.generalizedFusionMinRelativeStrength!==void 0?{minRelativeStrength:B.retrieval.generalizedFusionMinRelativeStrength}:{},maxCandidates:32,maxTotalFacts:32}:void 0,V=J,O;if($!==void 0)O=$==="conversational"?"conversational":"kept_existing";else if(B.adapters?.assistedExtractor)O="kept_existing";else if(B.assistedExtractorModelConfigured)V="conversational",O="conversational";else O="unavailable";return{extractionMode:V,...B.providerRerankerConfigured?{providerRerankingStrategy:"listwise"}:{},retrieval:{autoStrategyBias:"hybrid",bm25Ranking:B.retrieval.bm25Ranking,generalizedFusion:k,preset:{active:!0,extraction:O,requested:"recommended"},...W?{rerankGeneralizedFusion:W}:{},semanticCandidates:X}}}var y=".goodmemory/memory.sqlite",f="GOODMEMORY_STORAGE_PROVIDER",m="GOODMEMORY_STORAGE_URL",H="GOODMEMORY_EMBEDDING",z="GOODMEMORY_ASSISTED_EXTRACTOR";function Y(B){if(!B)return;let $=B.trim();return $.length>0?$:void 0}function c(B){return B?.provider!==void 0||Y(B?.url)!==void 0}function v(B){return Boolean(B?.assistedExtractor||B?.documentStore||B?.embeddingAdapter||B?.reranker||B?.recallPlanner||B?.sessionStore||B?.vectorStore)}function g(B){let $=[];if(B?.documentStore)$.push("documentStore");if(B?.sessionStore)$.push("sessionStore");if(B?.vectorStore)$.push("vectorStore");return $}function U(B){let $=B;if($===void 0||$==="memory"||$==="sqlite"||$==="postgres")return $;throw Error(`Unsupported storage provider: ${$}. Expected memory|sqlite|postgres.`)}function d(B,$){let J=Y(B?.url);if(B?.provider!==void 0||J!==void 0)return{provider:U(B?.provider),url:J};return{provider:U(Y($[f])),url:Y($[m])}}function l(){return typeof globalThis.Bun<"u"}function s(){return typeof globalThis.Bun<"u"}function E(B){let $=B?.builtInSQLite??B?.localDefaultSQLite??l(),J=B?.builtInPostgres??s(),Z=B?.localDefaultSQLite??$;return{builtInPostgres:J,builtInSQLite:$,localDefaultSQLite:Z}}function a(B){return/^(?:postgres|postgresql):\/\//i.test(B.trim())}function F(B,$=process.cwd()){let J=Y(B);if(!J)return L($,y);return J===":memory:"?J:L($,J)}function p(B){let $=B.env??process.env,J=B.cwd??process.cwd(),Z=E(B.runtimeCapabilities).localDefaultSQLite,j=d(B.storage,$),X=j.provider,k=j.url;if(X==="memory")return{mode:"explicit",storage:{provider:"memory"}};if(X==="sqlite")return{mode:"explicit",storage:{provider:"sqlite",url:F(k,J)}};if(X==="postgres"){if(!k)throw Error("Postgres storage provider requires storage.url to be configured.");return{mode:"explicit",storage:{provider:"postgres",url:k}}}if(k&&a(k)){if(!Z)return{mode:"auto",fallbackProvider:"memory",postgresUrl:k};return{mode:"auto",postgresUrl:k,sqliteUrl:F(void 0,J)}}if(!k&&!Z)return{mode:"auto",fallbackProvider:"memory",postgresUrl:void 0};return{mode:"auto",postgresUrl:void 0,sqliteUrl:F(k,J)}}function I(B){let $=B.env??process.env,J=E(B.runtimeCapabilities),Z=B.config.adapters?.embeddingAdapter?null:o(B.config.providers?.embedding)??n($),j=B.config.adapters?.assistedExtractor?null:r(B.config.providers?.extraction)??t($),X=B.config.adapters?.reranker?null:u(B.config.providers?.reranking),k=Boolean(B.config.adapters?.embeddingAdapter||Z),W=x({adapters:B.config.adapters,assistedExtractorModelConfigured:Boolean(j),embeddingEnabled:k,extraction:B.config.providers?.extraction,providerRerankerConfigured:Boolean(X),retrieval:B.config.retrieval});return{assistedExtractionEnabled:Boolean(B.config.adapters?.assistedExtractor||j),assistedExtractorModelConfig:j,embeddingEnabled:k,embeddingModelConfig:Z,rerankerModelConfig:X,rerankingEnabled:Boolean(B.config.adapters?.reranker||X),...W.providerRerankingStrategy?{providerRerankingStrategy:W.providerRerankingStrategy}:{},extractionMode:W.extractionMode,retrieval:W.retrieval,explicitAdaptersConfigured:v(B.config.adapters),explicitStorageConfigured:c(B.config.storage),runtimeCapabilities:J,storageAdapterOverrides:g(B.config.adapters),storagePlan:p({storage:B.config.storage,env:$,cwd:B.cwd,runtimeCapabilities:J})}}function u(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0||!$||!J||!Z)throw Error(`Missing required providers.reranking configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported reranking provider: ${$}. Expected one of openai|anthropic.`);return{apiKey:Z,baseURL:j,model:J,provider:$}}function o(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0)throw Error(`Missing required providers.embedding configuration fields: ${X.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required providers.embedding configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported embedding provider: ${$}. Expected one of openai.`);if($!=="openai")throw Error(`Unsupported embedding provider: ${$}. GoodMemory currently supports openai embeddings only.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function r(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0)throw Error(`Missing required providers.extraction configuration fields: ${X.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required providers.extraction configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported extraction provider: ${$}. Expected one of openai|anthropic.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function n(B=process.env){let $=Y(B[`${H}_PROVIDER`]),J=Y(B[`${H}_MODEL`]),Z=Y(B[`${H}_API_KEY`]),j=Y(B[`${H}_BASE_URL`]);if(!Boolean($||J||Z||j))return null;let k=[!$?`${H}_PROVIDER`:null,!J?`${H}_MODEL`:null,!Z?`${H}_API_KEY`:null].filter(Boolean);if(k.length>0){let D=j&&k.length===1&&!Z?" (local OpenAI-compatible endpoints such as Ollama accept any placeholder value, e.g. GOODMEMORY_EMBEDDING_API_KEY=ollama)":"";throw Error(`Missing required ${H} environment variables: ${k.join(", ")}${D}`)}if(!$||!J||!Z)throw Error(`Missing required ${H} environment variables: ${k.join(", ")}`);if(!T($))throw Error(`Unsupported embedding provider: ${$}. Expected one of openai.`);if($!=="openai")throw Error(`Unsupported embedding provider: ${$}. GoodMemory currently supports openai embeddings only.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function t(B=process.env){let $=Y(B[`${z}_PROVIDER`]),J=Y(B[`${z}_MODEL`]),Z=Y(B[`${z}_API_KEY`]),j=Y(B[`${z}_BASE_URL`]);if(!Boolean($||J||Z||j))return null;let k=[!$?`${z}_PROVIDER`:null,!J?`${z}_MODEL`:null,!Z?`${z}_API_KEY`:null].filter(Boolean);if(k.length>0)throw Error(`Missing required ${z} environment variables: ${k.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required ${z} environment variables: ${k.join(", ")}`);if(!T($))throw Error(`Unsupported assisted extractor provider: ${$}. Expected one of openai|anthropic.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}var M=Symbol.for("goodmemory.runtime.info");function e(B){let{runtimeCapabilities:$,storageAdapterOverrides:J,storagePlan:Z}=B;if(J.length>0)return{mode:"adapter",primaryProvider:"adapter",durability:"adapter_defined",overriddenStores:[...J]};if(Z.mode==="explicit"){if(Z.storage.provider==="memory")return{mode:"explicit",primaryProvider:"memory",durability:"ephemeral",postgresConfigured:!1};if(Z.storage.provider==="sqlite"){if(!$.builtInSQLite)return{mode:"explicit",primaryProvider:"sqlite",durability:"unavailable",postgresConfigured:!1,sqliteUrl:Z.storage.url,unavailableReason:"runtime_without_builtin_sqlite"};return{mode:"explicit",primaryProvider:"sqlite",durability:"durable",postgresConfigured:!1,sqliteUrl:Z.storage.url}}if(!$.builtInPostgres)return{mode:"explicit",primaryProvider:"postgres",durability:"unavailable",postgresConfigured:!0,unavailableReason:"runtime_without_builtin_postgres"};return{mode:"explicit",primaryProvider:"postgres",durability:"durable",postgresConfigured:!0}}if("sqliteUrl"in Z){if(!Z.postgresUrl&&!$.builtInSQLite)return{mode:"auto",primaryProvider:"sqlite",durability:"unavailable",postgresConfigured:!1,sqliteUrl:Z.sqliteUrl,unavailableReason:"runtime_without_builtin_sqlite"};if(Z.postgresUrl)return{mode:"auto",primaryProvider:"postgres",fallbackProvider:"sqlite",durability:"durable",postgresConfigured:!0,sqliteUrl:Z.sqliteUrl};return{mode:"auto",primaryProvider:"sqlite",durability:"durable",postgresConfigured:!1,sqliteUrl:Z.sqliteUrl}}if(Z.postgresUrl)return{mode:"auto",primaryProvider:"postgres",fallbackProvider:"memory",durability:"conditional",fallbackReason:"runtime_without_local_sqlite",postgresConfigured:!0};return{mode:"auto",primaryProvider:"memory",durability:"ephemeral",fallbackReason:"runtime_without_local_sqlite",postgresConfigured:!1}}function i(B){return{assistedExtractionEnabled:B.assistedExtractionEnabled,embeddingEnabled:B.embeddingEnabled,explicitAdaptersConfigured:B.explicitAdaptersConfigured,explicitStorageConfigured:B.explicitStorageConfigured,...B.retrieval.preset?{retrievalPreset:B.retrieval.preset}:{},storage:e(B)}}function TB(B){return i(I(B))}function VB(B,$){return B[M]=$,B}function QB(B){return B[M]}
export{P as ca,JB as da,q as ea,A as fa,ZB as ga,N as ha,XB as ia,I as ja,i as ka,TB as la,VB as ma,QB as na};
export interface ReferencePointerOccurrence {
index: number;
pointer: string;
}
export declare function parseReferencePointer(value: string | undefined): string | undefined;
export declare function extractReferencePointerOccurrences(value: string | undefined): ReferencePointerOccurrence[];
export declare function extractReferencePointers(value: string | undefined): string[];
export declare function extractReferencePointer(value: string | undefined): string | undefined;
export declare const CHINESE_ANALYZER_VERSION = "12-directive-pointer-boundary";
export declare function normalizeChineseForEquality(text: string): string;
export declare function tokenizeChineseForScoring(text: string, locale: string): string[];
export declare function buildChineseSearchTerms(text: string, locale: string): string[];
import type { LanguageContentAnalysis, LanguageDetectionStrength, LanguageEntityMention, LanguageQueryAnalysis, LanguageRenderInput, LanguageTemporalExpression } from "./contracts";
export type ChineseScript = "Hans" | "Hant";
export declare function detectChinese(texts: readonly string[], script: ChineseScript): LanguageDetectionStrength;
export declare function analyzeChineseQuery(query: string): LanguageQueryAnalysis;
export declare function analyzeChineseContent(content: string): LanguageContentAnalysis;
export declare function decomposeChineseQuery(query: string): string[];
export declare function parseChineseTemporalExpressions(text: string): LanguageTemporalExpression[];
export declare function extractChineseEntityMentions(text: string): LanguageEntityMention[];
export declare function renderChinese(input: LanguageRenderInput, script: ChineseScript): string;
import type { LanguageBehavioralRuleAnalysis } from "./contracts";
import { type BehavioralRulePatterns } from "./packHelpers";
export declare function analyzeEnglishBehavioralRule(rule: string, patterns: BehavioralRulePatterns): LanguageBehavioralRuleAnalysis;
import type { LanguageContentAnalysis, LanguageEntityCandidateInput, LanguageEntityMention, LanguageQueryAnalysis, LanguageRenderInput, LanguageTemporalExpression } from "./contracts";
export declare function analyzeEnglishQuery(query: string): LanguageQueryAnalysis;
export declare function analyzeEnglishContent(content: string): LanguageContentAnalysis;
export declare function decomposeEnglishQuery(query: string): string[];
export declare function parseEnglishTemporalExpressions(text: string): LanguageTemporalExpression[];
export declare function extractEnglishEntityMentions(text: string): LanguageEntityMention[];
export declare function acceptsEnglishEntityCandidate(input: LanguageEntityCandidateInput): boolean;
export declare function renderEnglish(input: LanguageRenderInput): string;
import type { LanguageTemporalExpression } from "./contracts";
export declare function parseEnglishTemporalReference(text: string): LanguageTemporalExpression | undefined;
import type { LanguagePack } from "./contracts";
export declare function createFrenchLanguagePack(): LanguagePack;
import type { LanguagePack } from "./contracts";
export declare function createJapaneseLanguagePack(): LanguagePack;
import type { LanguagePack } from "./contracts";
export declare function createKoreanLanguagePack(): LanguagePack;
import type { MemoryCandidate } from "../domain/memoryCandidate";
import type { LanguageBehavioralRuleAnalysis, LanguageContentAnalysis, LanguageEntityMention, LanguageQueryAnalysis, LanguageRenderInput, LanguageRenderKey, LanguageSourceOfTruthDirective, LanguageTemporalExpression } from "./contracts";
export interface BehavioralRulePatterns {
firstAction: readonly RegExp[];
format: RegExp;
general: RegExp;
hostAction?: BehavioralHostActionPatterns;
negative: RegExp;
trigger?: readonly RegExp[];
}
export interface BehavioralHostActionPatterns {
destination: readonly RegExp[];
flags?: readonly RegExp[];
mode?: readonly RegExp[];
owner?: readonly RegExp[];
permissions?: readonly RegExp[];
sources?: readonly RegExp[];
tag?: readonly RegExp[];
verbs?: ReadonlyArray<{
pattern: RegExp;
value: string;
}>;
}
export declare function analyzeBehavioralRuleWithPatterns(text: string, patterns: BehavioralRulePatterns): LanguageBehavioralRuleAnalysis;
export declare function uniqueCapturedValues(text: string, patterns: readonly RegExp[]): string[];
export declare function emptyBehavioralRuleAnalysis(): LanguageBehavioralRuleAnalysis;
export declare function createSourceOfTruthReferenceCandidate(input: {
analysis: LanguageContentAnalysis | undefined;
nextId: () => string;
sourceMessageIndex: number;
subject?: string;
}): MemoryCandidate | undefined;
export declare function emptyQueryAnalysis(): LanguageQueryAnalysis;
export declare function emptyContentAnalysis(): LanguageContentAnalysis;
export declare function resolveSourceOfTruthDirective(text: string, matches: {
allowsEmbeddedStart?(index: number): boolean;
affirmed(index: number, pointerLength: number): boolean;
negated(index: number, pointerLength: number): boolean;
trimPointerSuffix?(pointer: string): string;
}): LanguageSourceOfTruthDirective | undefined;
export declare function splitSentencesGeneric(text: string): string[];
export declare function decomposeQueryByPattern(text: string, boundary: RegExp): string[];
export declare function extractPatternMentions(text: string, patterns: ReadonlyArray<{
kind?: LanguageEntityMention["kind"];
pattern: RegExp;
}>): LanguageEntityMention[];
export declare function matchesNormalizedEntityAlias(query: string, alias: string, normalize: (value: string) => string): boolean;
export declare function parseTechnicalTemporalExpressions(text: string): LanguageTemporalExpression[];
export declare function renderFromCatalog(input: LanguageRenderInput, catalog: Readonly<Record<LanguageRenderKey, string>>): string;
import type { LanguageContentAnalysis, LanguageEntityCandidateInput, LanguageEntityMention, LanguagePack, LanguageQueryAnalysis, LanguageRenderKey, LanguageTemporalExpression } from "./contracts";
import type { BehavioralRulePatterns } from "./packHelpers";
export interface RomanceTemporalPattern {
offset: number;
pattern: RegExp;
unit: "day" | "month" | "quarter" | "week" | "year";
}
export interface RomanceWordDate {
monthNames: readonly string[];
pattern: RegExp;
}
export interface RomanceCandidatePatterns {
explicitFact: RegExp;
feedback: RegExp;
goal: RegExp;
inferredFact: RegExp;
name: RegExp;
preference: RegExp;
role: RegExp;
}
export interface RomancePackDefinition {
behavioralRulePatterns: BehavioralRulePatterns;
analyzerVersion: string;
compatibilityGroup: string;
defaultLocale: string;
id: string;
locales: readonly string[];
stopwords: ReadonlySet<string>;
entityStopwords: ReadonlySet<string>;
distinctivePatterns: readonly RegExp[];
incompatiblePatterns: readonly RegExp[];
decompositionBoundary: RegExp;
analyzeQuery(text: string): LanguageQueryAnalysis;
analyzeContent(text: string): LanguageContentAnalysis;
temporalPatterns: readonly RomanceTemporalPattern[];
wordDate: RomanceWordDate;
candidatePatterns: RomanceCandidatePatterns;
renderCatalog: Readonly<Record<LanguageRenderKey, string>>;
}
export declare function detectLatinLanguage(texts: readonly string[], input: {
distinctivePatterns: readonly RegExp[];
incompatiblePatterns: readonly RegExp[];
}): "compatible" | "distinctive" | "none";
export declare function parseRomanceTemporalExpressions(text: string, input: {
locale: string;
patterns: readonly RomanceTemporalPattern[];
wordDate: RomanceWordDate;
}): LanguageTemporalExpression[];
export declare function extractLatinEntityMentions(text: string, stopwords: ReadonlySet<string>): LanguageEntityMention[];
export declare function acceptsLatinEntityCandidate(input: LanguageEntityCandidateInput, stopwords: ReadonlySet<string>): boolean;
export declare function createRomanceLanguagePack(definition: RomancePackDefinition): LanguagePack;
import type { LanguageContentAnalysis, LanguageService } from "./contracts";
export declare function containsSensitiveCredential(text: string, language?: LanguageService): boolean;
export declare function containsSensitiveCredentialFromAnalysis(text: string, analysis: LanguageContentAnalysis): boolean;
export declare function redactSensitiveCredentialText(text: string, language?: LanguageService): string;
import type { LanguagePack } from "./contracts";
export declare function createSpanishLanguagePack(): LanguagePack;
import type { LanguageTemporalExpression } from "./contracts";
export declare function parseCjkTemporalReference(text: string): LanguageTemporalExpression | undefined;
export type ModelUsageOperation = "answer_generation" | "assisted_extraction" | "embedding" | "judge" | "recall_plan" | "recall_router_plan" | "recall_router_rerank" | "reranker_listwise" | "reranker_pointwise";
export type ModelUsageCompleteness = "complete" | "missing" | "partial";
export interface ModelTokenUsage {
cacheCreationInputTokens: number | null;
cacheReadInputTokens: number | null;
inputTokens: number | null;
outputTokens: number | null;
uncachedInputTokens: number | null;
}
export interface ModelUsageAttempt {
attempt: number;
completeness: ModelUsageCompleteness;
modelId: string;
operation: ModelUsageOperation;
outcome: "failed" | "succeeded";
providerId: string;
schemaVersion: 1;
usage: ModelTokenUsage;
}
export interface ModelUsageIntent {
attempt: number;
modelId: string;
operation: ModelUsageOperation;
providerId: string;
schemaVersion: 1;
}
export interface ModelUsageSink {
begin?(intent: ModelUsageIntent): (event: ModelUsageAttempt) => void;
emit(event: ModelUsageAttempt): void;
strict?: boolean;
}
interface AISDKLanguageModelUsageLike {
inputTokenDetails?: {
cacheReadTokens?: number;
cacheWriteTokens?: number;
noCacheTokens?: number;
};
inputTokens?: number;
outputTokens?: number;
}
interface AISDKEmbeddingUsageLike {
tokens?: number;
}
export declare function normalizeAISDKLanguageModelUsage(usage: AISDKLanguageModelUsageLike | undefined): ModelTokenUsage;
export declare function normalizeAISDKEmbeddingUsage(usage: AISDKEmbeddingUsageLike | undefined): ModelTokenUsage;
export declare function normalizeOpenAICompatibleUsage(payload: unknown): ModelTokenUsage;
export declare function modelUsageCompleteness(usage: ModelTokenUsage): ModelUsageCompleteness;
export declare function modelTokenTotal(usage: ModelTokenUsage): number | null;
export declare function runWithModelUsageAttempt<T>(input: {
attempt: number;
modelId: string;
operation: ModelUsageOperation;
providerId: string;
run(report: (usage: ModelTokenUsage) => void): Promise<T>;
sink?: ModelUsageSink;
}): Promise<T>;
export {};
import { generateObject } from "ai";
import { z } from "zod";
import type { RecallPlanAssistant, RecallPlanAssistantInput } from "../recall/recallPlan";
import { resolveAISDKModel } from "./ai-sdk-runtime";
import type { ModelUsageSink } from "./model-usage";
import type { AISDKModelConfig, AISDKRetryOptions, FetchLike } from "./ai-sdk-runtime";
export declare const recallPlanAssistanceSchema: z.ZodObject<{
aggregation: z.ZodOptional<z.ZodEnum<{
current: "current";
change: "change";
count: "count";
history: "history";
}>>;
entities: z.ZodOptional<z.ZodArray<z.ZodString>>;
evidenceNeeds: z.ZodOptional<z.ZodArray<z.ZodEnum<{
aggregation: "aggregation";
direct: "direct";
multi_facet: "multi_facet";
relation: "relation";
temporal: "temporal";
}>>>;
facets: z.ZodOptional<z.ZodArray<z.ZodString>>;
maxHops: z.ZodOptional<z.ZodNumber>;
planes: z.ZodOptional<z.ZodArray<z.ZodEnum<{
runtime: "runtime";
semantic: "semantic";
episodic: "episodic";
procedural: "procedural";
derived: "derived";
}>>>;
temporalConstraints: z.ZodOptional<z.ZodArray<z.ZodObject<{
kind: z.ZodEnum<{
current: "current";
before: "before";
history: "history";
after: "after";
}>;
referenceTime: z.ZodString;
}, z.core.$strict>>>;
uncertainty: z.ZodOptional<z.ZodEnum<{
high: "high";
low: "low";
medium: "medium";
}>>;
}, z.core.$strict>;
export declare const RECALL_PLAN_ASSISTANT_SYSTEM_PROMPT: string;
export interface RecallPlanAssistantDependencies {
fetch?: FetchLike;
generateObject?: typeof generateObject;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;
resolveModel?: typeof resolveAISDKModel;
retryOptions?: AISDKRetryOptions;
}
export declare function buildRecallPlanAssistantPrompt(input: RecallPlanAssistantInput): string;
export declare function createLLMRecallPlanAssistant(input: {
dependencies?: RecallPlanAssistantDependencies;
maxOutputTokens?: number;
model: AISDKModelConfig;
system?: string;
temperature?: number;
}): RecallPlanAssistant;
import type { EvidenceRecord } from "../evidence/contracts";
import type { ClaimProjection } from "./projections/contracts";
import type { RecallAggregation } from "./recallPlan";
export interface EvidenceLedgerEntry {
evidenceId: string;
sourceMemoryId: string;
actor?: string;
excerpt: string;
claim?: ClaimProjection;
temporalStatus: "current" | "superseded" | "uncertain";
relation: "supports" | "contradicts" | "context";
}
export interface BuildEvidenceLedgerInput {
aggregation?: RecallAggregation;
ambiguousSourceMemoryIds?: readonly string[];
claims: readonly ClaimProjection[];
evidence: readonly EvidenceRecord[];
referenceTime: string;
selectedMemoryIds: readonly string[];
}
export declare function buildEvidenceLedger(input: BuildEvidenceLedgerInput): EvidenceLedgerEntry[];
import type { MemoryScope } from "../../domain/scope";
import type { EvidenceRecord } from "../../evidence/contracts";
import type { ProjectionCapableDocumentStore, StorageDocument } from "../../storage/contracts";
import type { LanguageService } from "../../language";
import type { AppendClaimProjectionInput, ClaimProjection, ClaimProjectionState } from "./contracts";
export interface ClaimProjectionIndex {
append(input: AppendClaimProjectionInput, state?: ClaimProjectionState): Promise<ClaimProjection | null>;
markFailed(input: AppendClaimProjectionInput, error: unknown): Promise<void>;
query(scope: MemoryScope): Promise<ClaimProjection[]>;
queryBySourceMemoryIds(scope: MemoryScope, sourceMemoryIds: readonly string[]): Promise<ClaimProjection[]>;
queryForSourceMemoryGroups(scope: MemoryScope, sourceMemoryIds: readonly string[]): Promise<ClaimProjection[]>;
queryHistory(scope: MemoryScope): Promise<ClaimProjection[]>;
search(scope: MemoryScope, query: string, limit: number, history: boolean, locale?: string): Promise<ClaimProjection[]>;
rebuildScope(input: {
scope: MemoryScope;
sources: readonly ClaimProjectionCanonicalSource[];
timestamp: string;
}): Promise<void>;
reconcileScope(input: {
canonicalSourceIds: ReadonlySet<string>;
scope: MemoryScope;
}): Promise<void>;
synchronizeFact(input: {
document: StorageDocument | null;
evidence?: readonly EvidenceRecord[];
fallbackScope?: MemoryScope;
sourceMemoryId: string;
timestamp: string;
}): Promise<void>;
}
export interface ClaimProjectionCanonicalSource {
collection: string;
document: StorageDocument;
evidence?: readonly EvidenceRecord[];
id: string;
}
export declare function buildClaimProjectionStatusId(scope: MemoryScope, sourceMemoryId: string): string;
export declare function buildClaimProjectionSearchText(input: {
contextualDescriptor?: string;
modality?: string;
objectEntity?: string;
objectText: string;
polarity?: string;
predicateKey: string;
subject: string;
}): string;
export declare function createClaimProjectionIndex(documentStore: ProjectionCapableDocumentStore, language: LanguageService): ClaimProjectionIndex;
import type { MemoryScope } from "../../domain/scope";
import type { LanguageService } from "../../language";
import type { DocumentWriteOperation, ProjectionCapableDocumentStore, StorageDocument } from "../../storage/contracts";
import { type RecallProjectionManifest } from "./contracts";
interface UnchangedDocument {
collection: string;
document: StorageDocument | null;
id: string;
}
export interface ProjectionManifestMutation {
set: DocumentWriteOperation[];
unchanged: UnchangedDocument[];
}
export interface ProjectionManifestTracker {
enabled: boolean;
beginValidation(scope: MemoryScope): Promise<RecallProjectionManifest | null>;
completeValidation(manifest: RecallProjectionManifest | null): Promise<boolean>;
hasValidProof(scope: MemoryScope): Promise<boolean>;
invalidate(scope: MemoryScope): Promise<void>;
prepareInvalidation(scopes: readonly MemoryScope[]): Promise<ProjectionManifestMutation>;
}
export declare function buildRecallProjectionBuildId(language: LanguageService): string | undefined;
export declare function createProjectionManifestTracker(input: {
buildId?: string;
documentStore: ProjectionCapableDocumentStore;
now: () => string;
}): ProjectionManifestTracker;
export {};
import type { ProjectionCapableDocumentStore } from "../../storage/contracts";
import { type RecallProjectionManifest } from "./contracts";
export declare function isProjectionValidationChangedError(error: unknown): boolean;
export interface ProjectionValidationFence {
documentStore: ProjectionCapableDocumentStore;
run<T>(manifest: RecallProjectionManifest, operation: () => Promise<T>): Promise<T>;
}
export declare function createProjectionValidationFence(documentStore: ProjectionCapableDocumentStore): ProjectionValidationFence;
import type { MemoryScope } from "../domain/scope";
import type { MemoryPlane } from "../domain/taxonomy";
import type { LanguageQueryAnalysis, LanguageService, ResolvedLanguageContext } from "../language";
export declare const RECALL_PLAN_PRE_RANK_LIMIT = 32;
export declare const RECALL_PLAN_SELECTED_LIMIT = 12;
export declare const RECALL_PLAN_MAX_RENDERED_TOKENS = 6000;
export type RecallAggregation = "change" | "count" | "current" | "history";
export type RecallEvidenceNeed = "aggregation" | "direct" | "multi_facet" | "relation" | "temporal";
export type RecallPlanUncertainty = "high" | "low" | "medium";
export interface TemporalConstraint {
kind: "after" | "before" | "current" | "history";
referenceTime: string;
}
export interface RecallPlan {
entities: string[];
facets: string[];
temporalConstraints: TemporalConstraint[];
aggregation?: RecallAggregation;
evidenceNeeds: RecallEvidenceNeed[];
planes: MemoryPlane[];
maxHops: number;
preRankLimit: number;
selectedLimit: number;
maxRenderedTokens: number;
uncertainty: RecallPlanUncertainty;
}
export interface BuildRecallPlanInput {
language?: LanguageService;
languageContext?: ResolvedLanguageContext;
locale?: string;
query: string;
queryAnalysis?: LanguageQueryAnalysis;
referenceTime: string;
scope: MemoryScope;
}
export interface RecallPlanAssistantInput {
deterministicPlan: RecallPlan;
locale?: string;
query: string;
referenceTime: string;
scope: MemoryScope;
}
export interface RecallPlanAssistant {
plan(input: RecallPlanAssistantInput): Promise<Partial<RecallPlan>>;
}
export interface RecallPlanResolution {
assistantApplied: boolean;
fallbackReason?: "assistant_error";
plan: RecallPlan;
}
export declare function buildUnplannedRecallPlan(): RecallPlan;
/**
* Build the provider-free recall plan from request-local information only.
* Benchmark labels, case ids, expected answers, and retrieved memories are not
* inputs, so this plan can be reproduced before retrieval starts.
*/
export declare function buildDeterministicRecallPlan(input: BuildRecallPlanInput): RecallPlan;
export declare function resolveRecallPlan(input: {
assistant?: RecallPlanAssistant;
input: BuildRecallPlanInput;
}): Promise<RecallPlanResolution>;
import type { SessionArchive } from "../domain/evolutionRecords";
import type { EpisodeMemory, FactMemory, ReferenceMemory } from "../domain/records";
import type { EvidenceRecord } from "../evidence/contracts";
import type { ClaimProjection } from "./projections/contracts";
import type { RecallAggregation } from "./recallPlan";
export type RecallRerankCollection = "episodes" | "facts" | "references" | "session_archives";
export type RecallRerankRecord = EpisodeMemory | FactMemory | ReferenceMemory | SessionArchive;
export interface RecallRerankCandidate {
collection: RecallRerankCollection;
firstStageScore?: number;
firstStageSelected: boolean;
key: string;
record: RecallRerankRecord;
retrievalText?: string;
}
export interface RecallRerankPool {
aggregation?: RecallAggregation;
candidates: RecallRerankCandidate[];
claims: ClaimProjection[];
evidence: EvidenceRecord[];
explicitEvidenceIds: string[];
includeEvidence: boolean;
laneCaps: Record<RecallRerankCollection, number>;
referenceTime: string;
}
export declare function recallRerankCandidateKey(collection: RecallRerankCollection, memoryId: string): string;
export declare function matchesRecallRerankCandidateId(candidateId: string, collection: RecallRerankCollection, memoryId: string): boolean;
export declare function setRecallRerankPool<T extends object>(result: T, pool: RecallRerankPool): T;
export declare function getRecallRerankPool(result: object): RecallRerankPool | undefined;
export declare function findAmbiguousRecallRerankMemoryIds(candidates: readonly RecallRerankCandidate[]): Set<string>;
export declare function copyRecallRerankPool<T extends object>(source: object, target: T): T;
export declare function normalizeRecallRerankText(values: readonly (string | undefined)[]): string | undefined;
export declare function mergeRecallRerankPools<T extends object>(input: {
preRankLimit: number;
primaryReserveLimit: number;
results: readonly object[];
target: T;
}): T;
import type { LanguageTemporalExpression } from "../language";
export declare function resolveTemporalReference(expressions: readonly LanguageTemporalExpression[], referenceTime: string): string | undefined;
import type { MemoryScope } from "../domain/scope";
import type { ProjectionCapableDocumentStore } from "../storage/contracts";
import type { ExtractionOutcome } from "./contracts";
export declare const EXTRACTION_CURSORS_COLLECTION = "extraction_cursors_v1";
export interface ExtractionCursorAttempt {
attempts: number;
errorCode?: string;
outcome: ExtractionOutcome;
through: number;
updatedAt: string;
}
export interface ExtractionCursor {
committedThrough: number;
id: string;
lastAttempt: ExtractionCursorAttempt;
schemaVersion: 1;
scopeKey: string;
sourceId: string;
}
export interface ExtractionCursorStore {
get(scope: MemoryScope, sourceId: string): Promise<ExtractionCursor | null>;
record(input: {
errorCode?: string;
outcome: ExtractionOutcome;
scope: MemoryScope;
sourceId: string;
through: number;
}): Promise<ExtractionCursor>;
}
export declare function createExtractionCursorStore(input: {
documentStore: ProjectionCapableDocumentStore;
now: () => string;
}): ExtractionCursorStore;
import type { LanguageContentAnalysis, LanguageService, ResolvedLanguageContext } from "../language";
import type { MemoryCandidate, MemoryExtractionInput } from "./candidates";
export interface RememberSourceLanguageAnalysis {
analysis: LanguageContentAnalysis;
context: ResolvedLanguageContext;
}
export type RememberSourceLanguageAnalyses = ReadonlyMap<number, RememberSourceLanguageAnalysis>;
export declare function analyzeRememberSourceMessages(input: MemoryExtractionInput, language: LanguageService): RememberSourceLanguageAnalyses;
export declare function candidateSourceLanguageAnalysis(candidate: MemoryCandidate, analyses: RememberSourceLanguageAnalyses): RememberSourceLanguageAnalysis | undefined;
export declare function primarySourceLanguageAnalysis(input: MemoryExtractionInput, analyses: RememberSourceLanguageAnalyses): RememberSourceLanguageAnalysis | undefined;
export declare function storedTextLanguageKey(text: string, locale?: string): string;
import { type DocumentStore } from "../storage/contracts";
import type { RollbackAction } from "./contracts";
export interface RememberWriteCoordinator {
deleteDocument(collection: string, id: string): Promise<void>;
releaseOwnership(): Promise<void>;
rollbackActions: RollbackAction[];
setDocument<TDocument extends object>(collection: string, id: string, document: TDocument): Promise<void>;
}
export declare function createRememberWriteCoordinator(documentStore: DocumentStore): RememberWriteCoordinator;
import type { MemoryScope } from "../domain/scope";
import type { ProjectionCapableDocumentStore, StorageDocument } from "./contracts";
export declare const SCOPE_DELETION_LOCKS_COLLECTION = "scope_deletion_locks_v1";
export declare const SCOPE_MUTATION_BARRIERS_COLLECTION = "scope_mutation_barriers_v1";
export declare const SCOPE_MUTATION_INTENTS_COLLECTION = "scope_mutation_intents_v1";
export declare function scopeDeletionLockId(scope: MemoryScope): string;
export declare function scopeDeletionLockIdsForDocument(document: StorageDocument): string[];
export interface ScopeDeletionCoordinator {
runExclusive<T>(scope: MemoryScope, operation: () => Promise<T>, options?: ScopeDeletionRunOptions): Promise<T>;
runMutation<T>(scope: MemoryScope, operation: () => Promise<T>): Promise<T>;
}
export interface ScopeDeletionRunOptions {
operationKey?: string;
resumeInterrupted?: {
confirmPriorRuntimesStopped: true;
};
}
export declare function createScopeDeletionAwareDocumentStore(documentStore: ProjectionCapableDocumentStore, config?: {
allowLockedBatchSet?: (input: {
batch: import("./contracts").ConditionalDocumentWriteBatch;
operation: import("./contracts").DocumentWriteOperation;
}) => boolean;
}): ProjectionCapableDocumentStore;
export interface ScopeDeletionCoordinatorConfig {
ownerId?: string;
}
export declare function createScopeDeletionCoordinator(documentStore: ProjectionCapableDocumentStore, config?: ScopeDeletionCoordinatorConfig): ScopeDeletionCoordinator;
import type { StorageDocument } from "./contracts";
export declare function tokenizeDocumentSearch(value: string): string[];
export declare function buildDocumentSearchQuery(value: string): string;
export declare function buildPostgresDocumentSearchTerms(value: string): {
substrings: string[];
tsQuery: string;
};
export declare function readDocumentSearchText(document: StorageDocument, field: string): string | undefined;
export declare function scoreDocumentSearch(query: string, text: string): number;
export declare function estimateTextTokens(value: string): number;
export declare function truncateTextToEstimatedTokens(value: string, maxTokens: number): string;
# GoodMemory 0.6 to 0.7 Migration Guide
GoodMemory 0.7 is a clean breaking replacement of the former partial language
adapter with one end-to-end `LanguagePack` contract. It does not provide an
adapter compatibility layer, dual-write mode, or feature flag. Plan the
upgrade as a coordinated code, configuration, and derived-projection change.
The 0.6 release remains the current rollback artifact until 0.7 passes its
release gate. Its benchmark reports are historical 0.6 evidence; they do not
establish 0.7 correctness or performance.
## Before upgrading
1. Pin the exact 0.6 application and GoodMemory versions.
2. Stop GoodMemory writers for the scopes being upgraded, or use an
application maintenance window that prevents a 0.6 and 0.7 process from
sharing one store.
3. Back up the canonical store and installed-host configuration. A completed
0.7 migration deletes old per-scope derived projections, so a downgrade
after cutover requires this snapshot.
4. Record custom language adapter/detector behavior and every locale passed by
the application or installed host.
5. Verify enough free storage for a second derived projection generation while
a scope is being rebuilt.
Do not point 0.6 and 0.7 runtimes at the same writable store. There is no mixed
version compatibility contract.
## Replace language configuration
Remove the 0.6 language-adapter configuration and any `adapterId` assumptions.
Configure the default and optional custom packs through `language`:
```ts
import { createGoodMemory } from "goodmemory";
const memory = createGoodMemory({
language: {
defaultLocale: "zh-TW",
detection: "auto",
packs: [productLanguagePack],
},
});
```
`LanguageConfig` has this 0.7 shape:
```ts
interface LanguageConfig {
defaultLocale?: string;
detection?: "auto" | "default_only";
detector?: LocaleDetector;
detectorVersion?: string;
packs?: readonly LanguagePack[];
}
```
The default locale is `en-US`. Explicit per-operation locale takes precedence.
If the host knows the language, pass it rather than asking detection to guess:
```ts
await memory.remember({
locale: "ja-JP",
scope,
messages,
});
await memory.recall({
locale: "ja-JP",
scope,
query,
});
```
Installed Codex/Claude hosts should set the same default during setup or
installation with `--default-locale <locale>`. Existing managed host config can
be regenerated by the 0.7 installer; do not hand-merge obsolete language
adapter fields into the generated block.
## Port a custom language implementation
A custom pack must implement the whole `LanguagePack` interface, not only
normalization or labels. Move all locale-specific detection, lexicons,
tokenization, query/content signals, time expressions, entity behavior,
candidate extraction, and rendering into the pack.
Registration rules are strict:
- reuse a built-in id and the same locale claims to replace that built-in;
- use a new id only for locales not already claimed by another effective pack;
- declare non-empty, canonical `defaultLocale`, `locales`, `apiVersion`,
`analyzerVersion`, and `compatibilityGroup` identity;
- keep callbacks deterministic and free of mutable external state;
- version a custom automatic detector with `detectorVersion`, otherwise the
analyzer manifest is non-persistable and cannot prove a complete projection.
Any change to normalization, tokenization, search terms, detection, sentence
boundaries, temporal interpretation, or entity canonicalization requires an
`analyzerVersion` bump and projection rebuild.
The `xx-Test` conformance/integration pack is the reference acceptance shape:
registering the pack alone must drive remember, projection, recall, and
buildContext without adding locale branches to business modules.
## Built-in language behavior changes
The built-ins are `en`, `zh-Hans`, `zh-Hant`, `ja`, `ko`, `fr`, and `es`.
- `zh-CN` and `zh-SG` resolve to Simplified Chinese.
- `zh-TW`, `zh-HK`, and `zh-MO` resolve to Traditional Chinese.
- bare `zh` uses a configured Chinese default when present, otherwise
`zh-Hans`.
- Kana is a distinctive Japanese signal.
- Hangul is a distinctive Korean signal.
- French and Spanish auto-detection requires language-specific grammatical,
diacritic, or punctuation evidence; unmarked Latin text uses the configured
default.
- unambiguous Hans/Hant characters may select the matching Chinese pack.
- ambiguous Han-only text uses the configured default instead of guessing.
- an unsupported explicit locale uses the neutral Unicode pack and does not
inherit English query/content semantics.
The 0.7 guarantee is script-local: Simplified query to Simplified source and
Traditional query to Traditional source. Simplified-to-Traditional and
Traditional-to-Simplified lexical recall are explicitly not guaranteed. There
is no OpenCC conversion, no handwritten conversion table, and no transformed
canonical text. If cross-script retrieval is required, use an embedding
channel or a future versioned `buildSearchTerms` implementation and rebuild
the derived projections.
## Migrate derived projections
0.7 uses a new projection generation:
| Projection | 0.7 collection generation |
|---|---|
| recall documents | v3 |
| entities / adjacency | v2 |
| claims and claim status | v2 |
| scope catalog | v2 |
Each derived record carries `searchText`, `searchLocale`, `languagePackId`,
`searchAnalyzerVersion`, and `searchSchemaVersion`. The scope catalog binds the
projection/search versions, active analyzer manifest, and canonical
source-generation proof.
Migration runs lazily on first recall or explicitly through maintenance:
```ts
await memory.runMaintenance({
scope,
jobs: ["projectionMigration"],
});
```
For each scope, 0.7 acquires the migration lock, rebuilds from canonical memory,
validates source/claim/status/evidence/entity coverage, and atomically marks
the new catalog complete. Until completion, recall does not read a partial new
generation; it uses the canonical repository fallback. A failed or interrupted
run is safe to repeat. After successful cutover, old projections and stale FTS
rows for that scope are deleted.
Canonical memory and raw user text are not rewritten. Missing old locale
provenance is repaired only for Kana or an unambiguous Hans/Hant signal;
ambiguous Han-only records keep their existing/default locale identity.
Run the explicit job scope by scope before opening traffic when predictable
first-request latency matters. A lazy migration is correct but may be slower
than a warm, pre-cutover rebuild.
## Application and output changes
- Read `locale`, `localeSource`, `languagePackId`, and analyzer/language pack
version provenance instead of language `adapterId`.
- Keep JSON keys stable; only human-readable context, evidence, journal,
fact/reference/episode, and installed-host text is localized.
- Do not persist `searchText` as canonical content or build application logic
around its exact token form. It is a versioned derived index value.
- Do not copy language rules into recall, storage, policy, or host modules.
Extend the pack and bump its analyzer identity.
- Treat `LanguageService.getAnalyzerManifest().persistable === false` as a
prohibition on durable completeness proof, not as permission to trust the
existing index.
## Declare custom-storage deletion semantics
`deleteAllMemory()` now fails before deleting anything when custom document,
session, or vector adapters are configured without an explicit terminal
deletion contract. Custom storage must provide the document, session, and
vector adapters as one complete bundle; mixing shared and runtime-local stores
cannot support cross-runtime deletion. The declaration is a caller assertion:
every cooperating GoodMemory runtime must point each of its document, session,
and vector adapters at the same corresponding shared backend, and the shared
projection-capable document-store namespace must own the persistent mutation
intents and deletion barriers:
```ts
const memory = createGoodMemory({
adapters: {
documentStore,
sessionStore,
vectorStore,
terminalDeletionSemantics: "shared-coordinated-backends-v1",
},
});
```
The declaration cannot prove remote adapter identity and does not make
uncoordinated external writers safe. Do not set it when any cooperating runtime
uses a process-local session/vector store, points an adapter at a different
backend, or writes directly without entering the same GoodMemory mutation
protocol. A false declaration can return success while leaving data behind.
Deletion ownership and mutation intents do not expire. An operation failure
persists a failed journal and keeps the scope closed; a hard process exit leaves
the journal in deleting state. After correcting the cause, stop every possible
old writer and deleter, then explicitly resume the same request:
```ts
await memory.deleteAllMemory({
scope,
includeRuntime: true,
resumeInterrupted: {
confirmPriorRuntimesStopped: true,
},
});
```
Recovery atomically verifies the canonical scope, deletion contract,
`includeRuntime` mode, lock/barrier generation, and interrupted mutation
intents before it starts the idempotent deletion again. Its `deleted` counts
cover the recovery attempt; records removed before the interruption are already
absent. Never set the confirmation while an old runtime may still be alive, and
never clear or replace a persisted owner merely because a timestamp is old:
without generation fencing in every document, session, and vector mutation, a
paused old owner could resume after takeover.
## Verification before cutover
Run the release commands from the 0.7 source identity you will publish:
```sh
bun test
bun run typecheck
bun run test:coverage
```
Also require the package/release/type-surface suites, packed-package consumer
smokes under Bun and Node 20, and a tarball smaller than 4 MiB. For every
enabled backend, test search/update/delete/conditional batch/repair/restart and
an interrupted/repeated projection migration.
PostgreSQL support for any non-English built-in pack is not accepted unless
the same candidate runs against a real `GOODMEMORY_TEST_POSTGRES_URL`, including
functional migration, scale, and `EXPLAIN` proof that the query uses the
version-matched `searchText` GIN index. A skipped PostgreSQL suite is a missing
gate, not a pass.
Check the multilingual scale gate with all seven built-in packs represented
and verify its declared p95/materialization/query-count/index-use thresholds. Do not infer
these results from the 0.6 English/Simplified-Chinese benchmark artifacts.
## Cutover and rollback
Cut over only after all scopes required for the deployment have complete,
version-matching projection proof and the 0.7 release gates are recorded.
Start only 0.7 writers after cutover.
If failure occurs before a scope is complete, stop 0.7, correct the issue, and
repeat migration; canonical memory has not changed. If failure occurs after
cutover, prefer a forward fix and rebuild. To run 0.6 again, stop every 0.7
process and restore the pre-upgrade store and host-configuration snapshot.
Do not reconstruct a downgrade from leftover derived collections and do not
introduce an adapter shim as an emergency compatibility path.
## Evidence boundary
The published 0.6 benchmark declarations, coverage report, package checksum,
and release workflow remain historical evidence for that exact version and
source identity. They must retain their 0.6 labels. A 0.7 release statement
requires fresh 0.7 package, runtime, storage, migration, scale, and consumer
evidence; old benchmark scores may be cited only as historical context unless
the full protocol is rerun and bound to the 0.7 artifact.
See [ADR-008](../adr/ADR-008-language-pack-horizontal-extension.txt) and the
[LanguagePack extension guide](./GoodMemory-LanguagePack-Extension-Guide.md)
for the architecture and pack authoring contracts.
# GoodMemory LanguagePack Extension Guide
GoodMemory treats language support as a vertical semantic boundary. A language
is not complete when only its labels or stopwords exist: the same
`LanguagePack` must govern write-time extraction, recall planning, lexical
search, entity matching, temporal interpretation, and context rendering.
## Built-in packs
The root package includes:
| Pack id | Locale claims | Compatibility group |
|---|---|---|
| `en` | `en` | `en` |
| `zh-Hans` | `zh-Hans`, `zh-CN`, `zh-SG` | `zh-Hans` |
| `zh-Hant` | `zh-Hant`, `zh-TW`, `zh-HK`, `zh-MO` | `zh-Hant` |
| `ja` | `ja` | `ja` |
| `ko` | `ko` | `ko` |
| `fr` | `fr` | `fr` |
| `es` | `es` | `es` |
Explicit per-call locale wins over detection. With `detection: "auto"`, kana
selects Japanese and script-specific Chinese characters select the matching
Chinese pack. Hangul selects Korean; distinctive French and Spanish grammar,
diacritics, or punctuation select their pack. Text containing only Han
characters, or Latin text without a language-specific signal, remains
ambiguous and resolves with `defaultLocale` instead of guessing.
Bare `zh` uses a configured Chinese default when present and otherwise resolves
to `zh-Hans`. Unsupported explicit locales resolve to the neutral Unicode pack;
they do not inherit English query or content semantics.
```ts
import { createGoodMemory } from "goodmemory";
const memory = createGoodMemory({
language: {
defaultLocale: "zh-TW",
detection: "auto",
},
});
await memory.remember({
locale: "ja-JP",
scope: { userId: "u-1" },
messages: [{ role: "user", content: "現在の役割はリリース責任者です。" }],
});
const recall = await memory.recall({
locale: "ja-JP",
scope: { userId: "u-1" },
query: "現在の役割は何ですか?",
});
```
`remember()` and `recall()` metadata expose the resolved locale, resolution
source, pack id, and analyzer version. Durable provenance stores the same
identity so later projection repair can reproduce the original analysis.
For a mixed-language `remember()` batch, each candidate and its evidence use
the pack resolved from that candidate's source message; the operation metadata
still describes the batch as a whole. Session archives persist their resolved
locale instead of trying to infer it later from a rendered summary.
## The extension contract
Custom packs implement the exported `LanguagePack` interface. Its methods form
one contract and should be tested together:
- identity: `id`, `apiVersion`, `analyzerVersion`, `compatibilityGroup`, locale
claims, and default locale
- routing: language detection and locale ownership
- lexical semantics: equality normalization, scoring tokens, bounded search
terms, clause splitting, and sentence splitting
- recall semantics: query decomposition, structured query intents, temporal
parsing and resolution, entity extraction, alias matching, and entity-candidate
eligibility
- write semantics: structured content signals such as durable/correction cues
and source-of-truth pointer transitions, plus candidate extraction
- presentation: localized render labels
Register a custom pack through `GoodMemoryConfig.language.packs`. To replace a
built-in pack, reuse its id and locale claims; a different id that claims an
already-owned locale is rejected at startup.
Pack identity and resolver configuration are canonicalized and snapshotted
when the service is created. Empty identity/default-locale fields are rejected,
and the service snapshots declared callbacks plus top-level enumerable pack
state. Pack callbacks run against that snapshot, so mutating the original
config or top-level pack fields later does not reconfigure the running service.
A pack is still a deterministic, versioned descriptor: its callbacks must not
depend on mutable external state, class-private state, or mutable nested
objects, which cannot be generically snapshotted. Close over immutable analyzer
data and construct a new service with a bumped `analyzerVersion` whenever those
semantics change.
```ts
import {
createEnglishLanguagePack,
createGoodMemory,
type LanguagePack,
} from "goodmemory";
const base = createEnglishLanguagePack();
const productEnglish: LanguagePack = {
...base,
analyzerVersion: "2-product-terms",
buildSearchTerms(text) {
return [...new Set([...base.buildSearchTerms(text), ...productTerms(text)])];
},
};
const memory = createGoodMemory({
language: {
defaultLocale: "en-US",
packs: [productEnglish],
},
});
function productTerms(text: string): string[] {
return text.includes("GM") ? ["goodmemory"] : [];
}
```
Keep search-term expansion deterministic and bounded. It is a candidate
generation aid, not a place for remote model calls or unbounded synonym graphs.
Terms are whitespace-delimited canonical tokens and are compared with a
locale-neutral Unicode case fold across storage backends. A pack must emit its
own locale-correct canonical form and must not encode a semantic distinction
only through letter case; storage does not perform language-specific stemming
or CJK segmentation.
If `language.detector` is configured in `auto` mode, also provide a stable
`detectorVersion`. Without it, `getAnalyzerManifest().persistable` is `false`
and a persistent projection proof must fail closed. A detector is ignored in
`default_only` mode, so it does not affect that mode's manifest eligibility.
## Chinese script-local contract
The two Chinese packs share implementation primitives but have distinct
compatibility groups and analyzer identities. Each pack normalizes and indexes
its own script. GoodMemory 0.7 guarantees Simplified query-to-Simplified source
and Traditional query-to-Traditional source behavior; it does not guarantee
Simplified-to-Traditional or Traditional-to-Simplified lexical recall.
There is no OpenCC dependency, generated conversion variant, or handwritten
partial conversion table. The exact user-authored text remains canonical and
displayable. If a later release adds cross-script expansion, it must do so as a
bounded `buildSearchTerms` change, bump the analyzer version, and rebuild
derived projections. An embedding channel can provide independent semantic
candidate generation, but it does not change the script-local lexical
contract.
## Projection and storage rules
Language-aware projection documents carry:
- raw `text`
- derived `searchText`
- `searchLocale`
- `languagePackId`
- `searchAnalyzerVersion`
- `searchSchemaVersion`
SQLite FTS and PostgreSQL GIN use `searchText` only for candidate admission.
Application-level scoring remains the final cross-backend ranking authority, so
storage-specific tokenizers cannot redefine recall semantics.
Changing normalization, tokenization, search-term generation, entity
canonicalization, detection, or sentence boundaries requires an
`analyzerVersion` bump.
Existing derived projections must then be rebuilt; canonical memory records and
their raw text remain unchanged. Treat missing or mismatched projection proof
as stale and rebuild fail-closed.
The 0.7 generation uses recall documents v3, entities/adjacency v2,
claims/status v2, and scope catalog v2. Migration is per scope and may run on
first recall or through the `projectionMigration` maintenance job. Until a new
catalog carries complete, version-matching analyzer/build/source-generation
proof, recall must not use a partial new generation and instead uses the
canonical repository fallback.
Interrupted migration is repeatable; successful cutover removes the old
scope's derived rows and stale FTS entries without changing canonical memory.
`LanguageService.getAnalyzerManifest()` returns a stable, sorted manifest of
the resolver configuration and every active pack, including the neutral
fallback. Its `resolutionOrder` separately preserves the effective pack lookup
order, while the sorted `packs` array keeps serialization deterministic. A
projection build may use the manifest only when `persistable` is `true`.
Projection build identity should hash that manifest together with the
projection/search schema and canonical source-generation proof; it must not
infer analyzer identity from one locale or one indexed document.
## Migration from the former language adapter
There is no compatibility adapter or per-module language switch. Migrate by:
1. moving every language-specific rule into a complete `LanguagePack`;
2. registering it through `language.packs` or replacing a built-in id;
3. passing explicit locale when the host knows it, especially for Han-only
text;
4. bumping `analyzerVersion` for semantic analyzer changes;
5. versioning any custom locale detector used by auto-detection;
6. rebuilding derived recall projections after analyzer or search-schema
changes; and
7. verifying provenance, same-script retrieval, explicit cross-script negative
cases, temporal planning, entity matching, and localized context output.
The optional `language.detector` remains a routing override only. It returns a
locale; it does not replace the pack's semantic responsibilities.
GoodMemory 0.7 does not run alongside a writable 0.6 process. Back up canonical
storage and managed host configuration before cutover; after a completed
migration, a downgrade requires that snapshot rather than a compatibility
adapter. Follow the [0.6 to 0.7 migration guide](./GoodMemory-0.6-to-0.7-Migration-Guide.md)
for the full cutover and rollback procedure.
## Acceptance checklist
A new pack is ready only when tests cover:
- explicit locale, auto-detection, default fallback, and ambiguous text;
- equality normalization and bounded search terms;
- write extraction and durable language provenance;
- query intent, decomposition, temporal expressions, and entity aliases;
- durable/correction cues and source-of-truth pointer transitions;
- a sentinel custom language whose non-English query and content signals drive
the same selection and remember paths without business-module changes;
- document, entity, and claim retrieval channels;
- SQLite and PostgreSQL `searchText` behavior where applicable;
- Simplified and Traditional same-script positive cases plus explicit
cross-script negative cases;
- interrupted, repeated, and concurrent projection migration with no orphaned
new-generation rows;
- context/evidence rendering and CJK token budgeting where applicable; and
- a real `remember -> recall -> buildContext` integration path.
A built-in or custom pack is not release-ready until the shared conformance
suite proves deterministic output, stable ordering, bounded search terms,
complete render keys, and a non-empty analyzer version. PostgreSQL support for
any non-English built-in pack additionally requires a real
`GOODMEMORY_TEST_POSTGRES_URL` functional, migration, scale, and `EXPLAIN`
index run; a skipped suite is not evidence.
+23
-39
{
"schemaVersion": "goodmemory.capability/v2",
"name": "goodmemory",
"version": "0.6.0",
"version": "0.7.0",
"kind": "memory-layer",

@@ -24,6 +24,12 @@ "summary": "Durable user/project memory layer for chat apps, copilots, and coding agents.",

"install": {
"npmGlobal": "npm install -g goodmemory@0.6.0",
"npmPackage": "npm install goodmemory@0.6.0",
"bun": "bun add goodmemory@0.6.0"
"npmGlobal": "npm install -g goodmemory@0.7.0",
"npmPackage": "npm install goodmemory@0.7.0",
"bun": "bun add goodmemory@0.7.0"
},
"releaseStatus": {
"installCommandsApplyAfterPublish": true,
"npmDistTag": "latest",
"status": "stable",
"tarball": "goodmemory-0.7.0.tgz"
},
"memoryApi": [

@@ -44,3 +50,3 @@ "remember",

"steps": [
"npm install -g goodmemory@0.6.0",
"npm install -g goodmemory@0.7.0",
"goodmemory setup",

@@ -111,37 +117,6 @@ "goodmemory status"

"benchmarks": {
"currentClaims": [
{
"name": "LoCoMo",
"config": "full 10 conversations, 1540 non-adversarial questions",
"metric": "independent official judge protocol; strict deterministic token-F1 reported separately",
"result": "official 0.8708; strict 0.6299; open-domain 0.6146 (59/96)",
"reference": "historical no-memory 0.0045",
"claimDeclaration": "https://github.com/hjqcan/GoodMemory/blob/main/benchmark-claims/locomo.json",
"runtimeProfile": "recommended+provider-embedding+provider-reranking@0.6.0",
"measuredPackageVersion": "0.6.0"
},
{
"name": "BEAM",
"config": "100K, 400 questions, 1051 rubric items",
"metric": "independent official unified-rubric score; strict binary and paper protocol disclosed separately",
"result": "unified 0.7651; strict 0.620 (248/400); generalized recall 0.8276",
"reference": "public full-400 same-protocol reference 0.49",
"claimDeclaration": "https://github.com/hjqcan/GoodMemory/blob/main/benchmark-claims/beam.json",
"runtimeProfile": "goodmemory-hybrid-generalized+evidence-pack@0.6.0",
"measuredPackageVersion": "0.6.0"
},
{
"name": "MemoryAgentBench",
"config": "Conflict Resolution 73 questions; Test-Time Learning 30 questions",
"metric": "deterministic upstream match-mode scoring, judge-free",
"result": "CR 0.959; TTL 0.933",
"reference": "no-memory 0.000 for CR and TTL",
"claimDeclaration": "https://github.com/hjqcan/GoodMemory/blob/main/benchmark-claims/memoryagentbench.json",
"runtimeProfile": "recommended-evidence-pack-cr-ttl@0.6.0",
"measuredPackageVersion": "0.6.0"
}
],
"currentClaims": [],
"historicalEvidence": {
"url": "https://github.com/hjqcan/GoodMemory/tree/main/benchmark-claims",
"note": "LongMemEval and ImplicitMemBench remain reproducible versioned internal evidence, not current-production claims for this package version."
"note": "The v0.6.0 LoCoMo, BEAM, and MemoryAgentBench results, plus older LongMemEval and ImplicitMemBench runs, remain reproducible versioned evidence. None is a current 0.7.0 production claim until rerun against this package line. LongMemEval and ImplicitMemBench remain internal evidence."
}

@@ -152,2 +127,11 @@ },

"embeddingFreeDefault": true,
"builtInLanguagePacks": [
"en",
"zh-Hans",
"zh-Hant",
"ja",
"ko",
"fr",
"es"
],
"durableStore": "sqlite (default), postgres (opt-in)",

@@ -162,4 +146,4 @@ "audit": true,

"benchmarks": "https://github.com/hjqcan/GoodMemory/tree/main/benchmark-claims",
"note": "This runtime descriptor exposes only claims accepted for the installed package version. Versioned historical results remain in benchmark-claims/*.json."
"note": "Benchmark entries keep explicit measuredPackageVersion provenance; a package version bump never relabels historical results. Source declarations remain in benchmark-claims/*.json."
}
}

@@ -1,4 +0,4 @@

import{S as Z,T as _,U as $,V as q,W as z,X as U}from"../chunk-z9fdphfn.js";import{_ as B,aa as r}from"../chunk-jamhwrr7.js";import{sa as d}from"../chunk-8f58rsqp.js";import"../chunk-jqpvhgjc.js";import"../chunk-cz5v71gv.js";import{Ab as N}from"../chunk-65h9nkw1.js";import"../chunk-jd15jhte.js";import"../chunk-84dyzpkj.js";import"../chunk-m205c7rp.js";async function k(A,E){let G=N(A);if(!G?.ingestAgentInputEvent)return{recorded:!1,skippedReason:"unsupported_memory"};return G.ingestAgentInputEvent({event:B(E)})}var I=160;function Q(A){return{role:"system",content:A}}function x(A){let{fragment:E,system:G}=A;if(!G)return E;if(typeof G==="string")return`${G}
import{S as Z,T as _,U as $,V as q,W as z,X as U}from"../chunk-s31bw0jc.js";import{_ as B,aa as r}from"../chunk-jamhwrr7.js";import{oa as d}from"../chunk-njm7jqas.js";import"../chunk-963r53yf.js";import"../chunk-8d816xbx.js";import{yb as N}from"../chunk-0h5pry7v.js";import"../chunk-jr0h5wkn.js";import"../chunk-c28647f0.js";import"../chunk-n9j0rb5c.js";import"../chunk-eqpe4gcb.js";async function k(A,E){let G=N(A);if(!G?.ingestAgentInputEvent)return{recorded:!1,skippedReason:"unsupported_memory"};return G.ingestAgentInputEvent({event:B(E)})}var I=160;function Q(A){return{role:"system",content:A}}function x(A){let{fragment:E,system:G}=A;if(!G)return E;if(typeof G==="string")return`${G}
${E}`;if(Array.isArray(G))return[...G,Q(E)];return[G,Q(E)]}function V(A){let E=A.trim();return E.length>0?E:null}function O(A){if(typeof A==="string")return V(A);let E=[];for(let G of A)if(G.type==="text"){let M=V(G.text);if(M)E.push(M)}return E.length>0?E.join(`
`):null}function b(A){for(let E=A.length-1;E>=0;E-=1){let G=A[E];if(!G||G.role!=="user")continue;let M=O(G.content);if(M)return M}return null}async function K(A,E){if(!A)return;try{await A(E)}catch(G){console.error("GoodMemory ai-sdk callback failed.",G)}}function F(A){return{phase:"recall",status:"skipped",reason:A.reason,scope:A.scope,retrievalProfile:A.retrievalProfile}}function j(A){return{phase:"remember",status:"skipped",reason:A.reason,scope:A.scope}}function T(A){return A.flatMap((E)=>{let G=O(E.content);if(!G)return[];return[{role:E.role,content:G}]})}function R(A){let E=A.result.events[0];if(E?.status==="applied")return{phase:"recall",status:"applied",scope:A.scope,retrievalProfile:A.retrievalProfile};return F({reason:f(E?.reason),retrievalProfile:A.retrievalProfile,scope:A.scope})}function f(A){if(A==="ignore_memory"||A==="no_query"||A==="empty_context")return A;return"empty_context"}async function W(A,E,G){let M=G.retrievalProfile??A.defaultRetrievalProfile??"general_chat",D=V(G.query??"")??b(G.messages);try{let S=await E.beforeModelCall({scope:G.scope,...D?{query:D}:{},locale:G.locale,ignoreMemory:G.ignoreMemory,retrievalProfile:M,maxMemoryTokens:G.maxMemoryTokens??A.defaultMaxMemoryTokens??I,messages:T(G.messages)});await K(A.onMemoryEvent,R({result:S,retrievalProfile:M,scope:G.scope}));let C=V(S.context.content);if(!C)return{retrievalProfile:M,system:G.system};return{retrievalProfile:M,system:x({system:G.system,fragment:C})}}catch(S){return await K(A.onMemoryError,{phase:"recall",scope:G.scope,error:S}),{retrievalProfile:M,system:G.system}}}async function X(A,E,G,M){let D=T(G.messages);if(G.ignoreMemory){await E.afterModelCall({scope:G.scope,locale:G.locale,messages:D,assistantText:M,writeback:{mode:"off"}}),await K(A.onMemoryEvent,j({reason:"ignore_memory",scope:G.scope}));return}let S=V(M);if(!S){await E.afterModelCall({scope:G.scope,locale:G.locale,messages:D,assistantText:M,writeback:{mode:"selective",annotation:"durable_candidate",policy:"allow"}}),await K(A.onMemoryEvent,j({reason:"no_final_assistant_text",scope:G.scope}));return}if(!b(G.messages)){await E.afterModelCall({scope:G.scope,locale:G.locale,messages:D,assistantText:S,writeback:{mode:"selective",annotation:"durable_candidate",policy:"allow"}}),await K(A.onMemoryEvent,j({reason:"no_text_messages",scope:G.scope}));return}try{let H=(await E.afterModelCall({scope:G.scope,locale:G.locale,messages:D,assistantText:S,writeback:{mode:"selective",annotation:"durable_candidate",policy:"allow"}})).rememberResult;if(!H){await K(A.onMemoryEvent,j({reason:"no_text_messages",scope:G.scope}));return}await K(A.onMemoryEvent,{phase:"remember",status:"succeeded",scope:G.scope,accepted:H.accepted,rejected:H.rejected})}catch(C){await K(A.onMemoryError,{phase:"remember",scope:G.scope,error:C})}}var y=new Set(["content","text","reasoning","reasoningText","files","sources","toolCalls","staticToolCalls","dynamicToolCalls","staticToolResults","dynamicToolResults","toolResults","finishReason","rawFinishReason","usage","totalUsage","warnings","steps","request","response","providerMetadata","output"]),m=new Set(["textStream","fullStream","experimental_partialOutputStream","partialOutputStream","elementStream"]);function g(A,E){return A().then((G)=>G[E])}async function c(A){let E=await A();if(typeof E.getReader==="function")return{reader:E.getReader()};return{iterator:E[Symbol.asyncIterator]()}}function h(A){let E=null,G=()=>{return E??=c(A),E},M=new ReadableStream({async pull(D){try{let S=await G(),C=S.reader?await S.reader.read():await S.iterator.next();if(C.done){S.reader?.releaseLock(),D.close();return}D.enqueue(C.value)}catch(S){D.error(S)}},async cancel(D){let S=await E;await S?.reader?.cancel(D),await S?.iterator?.return?.(),S?.reader?.releaseLock()}});return Object.assign(M,{async*[Symbol.asyncIterator](){let D=M.getReader();try{while(!0){let{done:S,value:C}=await D.read();if(S)break;yield C}}finally{D.releaseLock()}}})}function J(A,E){return h(async()=>{return(await A())[E]})}function l(A,E){return async(...G)=>{let M=await A();return M[E].apply(M,G)}}function Y(A){let{originalMessages:E,generateMessageId:G,onFinish:M,messageMetadata:D,sendReasoning:S,sendSources:C,sendFinish:H,sendStart:w,onError:v,...P}=A&&typeof A==="object"?A:{};return{responseInit:P,streamOptions:{originalMessages:E,generateMessageId:G,onFinish:M,messageMetadata:D,sendReasoning:S,sendSources:C,sendFinish:H,sendStart:w,onError:v}}}function L(A,E){return h(async()=>{return(await A()).toUIMessageStream(E)})}function a(A){let E=null,G=()=>{return E??=A(),E};return new Proxy({},{get(M,D){if(y.has(D))return g(G,D);if(m.has(D))return J(G,D);if(D==="consumeStream")return l(G,"consumeStream");if(D==="toUIMessageStream")return(S)=>L(G,S);if(D==="pipeUIMessageStreamToResponse")return(S,C)=>{let{responseInit:H,streamOptions:w}=Y(C);z({response:S,stream:L(G,w),...H})};if(D==="pipeTextStreamToResponse")return(S,C)=>{$({response:S,textStream:J(G,"textStream"),...C})};if(D==="toUIMessageStreamResponse")return(S)=>{let{responseInit:C,streamOptions:H}=Y(S);return q({stream:L(G,H),...C})};if(D==="toTextStreamResponse")return(S)=>_({textStream:J(G,"textStream"),...S});return}})}function o(A){let E=A.dependencies?.generateText??Z,G=A.dependencies?.streamText??U,M=d({memory:A.memory,defaultContextMode:"fragment",defaultMaxMemoryTokens:A.defaultMaxMemoryTokens??I});return{async generateText(D){let S=await W(A,M,D),C=D.onFinish;return E({...D,system:S.system,messages:D.messages,onFinish:async(H)=>{if(await X(A,M,D,H.text),C)await C(H)}})},streamText(D){return a(async()=>{let S=await W(A,M,D),C=D.onFinish;return G({...D,system:S.system,messages:D.messages,onFinish:async(H)=>{if(await X(A,M,D,H.text),C)await C(H)}})})}}}export{B as validateAgentInputEvent,r as isAgentInputEvent,k as ingestAgentInputEvent,o as createGoodMemoryAISDK};

@@ -11,2 +11,4 @@ /**

content: string;
/** LanguagePack-derived polarity. The answer domain never parses language. */
polarity: "negative" | "positive" | "unknown";
/** Source order. Higher = later. May be a chat index, chunk ordinal, or write sequence. */

@@ -13,0 +15,0 @@ orderKey: number;

@@ -0,1 +1,10 @@

export interface GoodMemoryPackageReleaseMetadata {
readonly installCommandsApplyAfterPublish: boolean;
readonly npmDistTag: string;
readonly status: "release-candidate" | "stable";
}
export interface GoodMemoryCapabilityPackageMetadata {
readonly goodmemoryRelease: GoodMemoryPackageReleaseMetadata;
readonly version: string;
}
export interface GoodMemoryCapabilityOnboardingPath {

@@ -48,2 +57,8 @@ readonly audience: string;

};
readonly releaseStatus: {
readonly installCommandsApplyAfterPublish: boolean;
readonly npmDistTag: string;
readonly status: "release-candidate" | "stable";
readonly tarball: string;
};
readonly memoryApi: readonly string[];

@@ -80,2 +95,3 @@ readonly onboarding: readonly GoodMemoryCapabilityOnboardingPath[];

readonly embeddingFreeDefault: boolean;
readonly builtInLanguagePacks: readonly string[];
readonly durableStore: string;

@@ -98,3 +114,4 @@ readonly audit: boolean;

export declare function buildGoodMemoryCapabilityDescriptor(options?: {
packageMetadata?: GoodMemoryCapabilityPackageMetadata;
version?: string;
}): GoodMemoryCapabilityDescriptor;

@@ -0,5 +1,6 @@

import type { EvidenceLedgerFormat } from "../answer/evidenceLedgerContext";
import type { MemoryScope } from "../domain/scope";
import type { ArtifactSpillRecord, EpisodeMemory, FactMemory, FeedbackKind, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionBuffer, SessionJournal, SessionMessage, UserProfile, WorkingMemorySnapshot } from "../domain/records";
import type { EmbeddingAdapter } from "../embedding/contracts";
import type { EvidenceRecord } from "../evidence/contracts";
import type { EvidenceRecord, SourceMessageRecord } from "../evidence/contracts";
import type { ExperienceRecord, LearningProposal, LearningProposalStatus, LearningProposalType, PromotionDecision, PromotionRecord, SessionArchive } from "../evolution/contracts";

@@ -12,2 +13,5 @@ import type { MarkdownArtifactBundle } from "../governance/markdownArtifacts";

import type { MemoryPacket } from "../recall/contextBuilder";
import type { EvidenceLedgerEntry } from "../recall/evidenceLedger";
import type { GeneralizedFusionChannel } from "../recall/generalizedFusion";
import type { RecallPlanAssistant } from "../recall/recallPlan";
import type { RecallCandidateTrace, RecallHit, RecallSemanticCandidatesConfig } from "../recall/engine";

@@ -61,2 +65,5 @@ import type { RecallAssistantInfluence } from "../recall/assistant";

preset?: GoodMemoryRetrievalPresetId;
generalizedFusionChannels?: readonly GeneralizedFusionChannel[];
generalizedFusionMinRelativeStrength?: number;
recallPlanExecution?: boolean;
bm25Ranking?: boolean;

@@ -78,3 +85,11 @@ semanticCandidates?: GoodMemorySemanticCandidatesConfig;

reranker?: Reranker;
recallPlanner?: RecallPlanAssistant;
sessionStore?: SessionStore;
/**
* Required before terminal deletion when custom storage adapters are used.
* Caller assertion: every cooperating runtime points documentStore,
* sessionStore, and vectorStore at the same corresponding shared backends,
* and every writer enters the GoodMemory mutation protocol.
*/
terminalDeletionSemantics?: "shared-coordinated-backends-v1";
vectorStore?: VectorStore;

@@ -99,2 +114,3 @@ };

locale?: string;
referenceTime?: string;
}

@@ -109,2 +125,3 @@ export interface RecallResult {

evidence: EvidenceRecord[];
evidenceLedger?: EvidenceLedgerEntry[];
episodes: EpisodeMemory[];

@@ -125,3 +142,4 @@ workingMemory: WorkingMemorySnapshot | null;

localeSource?: "explicit" | "detected" | "default";
adapterId?: string;
languagePackId?: string;
languagePackVersion?: string;
analysisMode?: "rules-only";

@@ -137,2 +155,3 @@ retrievalTrace?: RecallRetrievalTrace;

maxTokens?: number;
evidenceLedgerFormat?: EvidenceLedgerFormat;
suppressDuplicateEvidence?: boolean;

@@ -149,6 +168,3 @@ }

scope: MemoryScope;
messages: Array<{
role: string;
content: string;
}>;
messages: SessionMessage[];
annotations?: MessageAnnotation[];

@@ -162,2 +178,3 @@ extractionStrategy?: MemoryExtractionStrategy;

events: RememberPipelineResult["events"];
outcome?: RememberPipelineResult["outcome"];
warnings?: string[];

@@ -167,3 +184,4 @@ metadata?: {

localeSource: "explicit" | "detected" | "default";
adapterId: string;
languagePackId: string;
languagePackVersion?: string;
analysisMode: "rules-only";

@@ -224,2 +242,3 @@ requestedExtractionStrategy: MemoryExtractionStrategy;

includeRuntime?: boolean;
locale?: string;
}

@@ -240,2 +259,3 @@ export interface ExportMemoryResult {

evidence: EvidenceRecord[];
sourceMessages?: SourceMessageRecord[];
experiences: ExperienceRecord[];

@@ -254,2 +274,10 @@ proposals: LearningProposal[];

includeRuntime?: boolean;
/**
* Explicit recovery of a persisted interrupted deletion. Set this only
* after every runtime that could still own the old deletion or mutation
* attempt has terminated.
*/
resumeInterrupted?: {
confirmPriorRuntimesStopped: true;
};
}

@@ -302,3 +330,4 @@ export interface DeleteAllMemoryResult {

localeSource: "explicit" | "detected" | "default";
adapterId: string;
languagePackId: string;
languagePackVersion?: string;
analysisMode: "rules-only";

@@ -431,2 +460,3 @@ traceId?: string;

exportMemory(input: ExportMemoryInput): Promise<ExportMemoryResult>;
/** Requires a projection-capable document store so scoped deletion is terminal. */
deleteAllMemory(input: DeleteAllMemoryInput): Promise<DeleteAllMemoryResult>;

@@ -433,0 +463,0 @@ feedback(input: FeedbackInput): Promise<FeedbackResult>;

import type { RetrievalStrategyRolloutConfig } from "../governance/retrievalInternalRollout";
import type { RecallRouterAssistant } from "../recall/assistant";
import type { FactSelector } from "../recall/generalizedSelection";
import type { GoodMemory, GoodMemoryConfig } from "./contracts";

@@ -9,2 +10,4 @@ export interface InternalGoodMemoryOptions {

environment?: Record<string, string | undefined>;
/** Repo-only instance selector override for historical evaluation profiles. */
factSelector?: FactSelector;
projectionBulkBackfill?: boolean;

@@ -14,4 +17,5 @@ projectionWriteThrough?: boolean;

retrievalStrategyRollout?: RetrievalStrategyRolloutConfig;
runtimeCompactionExtraction?: boolean;
}
export declare function createGoodMemory(config: GoodMemoryConfig): GoodMemory;
export declare function createInternalGoodMemory(config: GoodMemoryConfig, internal?: InternalGoodMemoryOptions): GoodMemory;

@@ -10,2 +10,3 @@ import type { FeedbackKind } from "../domain/records";

import type { ProposalGateDecision } from "../evolution/gates";
import type { LanguageService } from "../language";
interface ReviewerRuntime {

@@ -43,2 +44,3 @@ review(input: {

governanceRepositories: GovernanceRepositoryPort;
language: LanguageService;
now?: () => string;

@@ -45,0 +47,0 @@ proposalGate: ProposalGateRuntime;

@@ -5,2 +5,3 @@ import type { AgentInputEvent, HostAgentEvent } from "../agentEvents";

import type { HostActionDecision, HostKind } from "../domain/hostTypes";
import type { LanguageService } from "../language";
import type { FeedbackPromotionReceipt, FeedbackProposalReceipt, GoodMemory } from "./contracts";

@@ -18,3 +19,4 @@ export declare const GOODMEMORY_INTEGRATION_SUPPORT: unique symbol;

localeSource: "explicit" | "detected" | "default";
adapterId: string;
languagePackId: string;
languagePackVersion?: string;
analysisMode: "rules-only";

@@ -65,2 +67,3 @@ };

export interface GoodMemoryIntegrationSupport {
readonly language: LanguageService;
ingestAgentInputEvent(input: {

@@ -67,0 +70,0 @@ event: AgentInputEvent;

@@ -1,10 +0,17 @@

import type { GoodMemory, GoodMemoryConfig } from "./contracts";
import type { GoodMemory, RecallInput } from "./contracts";
import type { LanguageQueryAnalysis, LanguageService, ResolvedLanguageContext } from "../language";
import { type RetrievalStrategyRolloutConfig } from "../governance/retrievalInternalRollout";
interface InternalRetrievalRolloutState {
assistedRecallRouterEnabled: boolean;
config: GoodMemoryConfig;
languageService: LanguageService;
now?: () => Date;
rollout?: RetrievalStrategyRolloutConfig;
}
interface InternalRecallLanguageAnalysis {
analysis: LanguageQueryAnalysis;
context: ResolvedLanguageContext;
query: string;
}
export declare function readInternalRecallLanguageAnalysis(input: RecallInput): InternalRecallLanguageAnalysis | undefined;
export declare function wrapInternalRetrievalRolloutMemory(memory: GoodMemory, state: InternalRetrievalRolloutState): GoodMemory;
export {};

@@ -0,1 +1,2 @@

import type { LanguageService } from "../language";
import type { GoodMemoryTracer } from "../observability/tracer";

@@ -6,2 +7,3 @@ import type { DocumentStore, SessionStore } from "../storage/contracts";

export type ScopeBoundRecord = {
id?: string;
userId: string;

@@ -20,5 +22,14 @@ tenantId?: string;

}
type ExportMemoryDeps = MemoryAdminDeps & {
language: LanguageService;
};
export declare function recordMatchesScope(record: ScopeBoundRecord, scope: ForgetInput["scope"]): boolean;
export declare function isPureUserScope(scope: ForgetInput["scope"]): boolean;
export declare function exportMemoryOperation(deps: MemoryAdminDeps, input: ExportMemoryInput): Promise<ExportMemoryResult>;
export declare function deleteMemorySupportingState(deps: Pick<MemoryAdminDeps, "documentStore">, input: {
collection: string;
memoryId: string;
scope: ForgetInput["scope"];
}): Promise<void>;
export declare function exportMemoryOperation(deps: ExportMemoryDeps, input: ExportMemoryInput): Promise<ExportMemoryResult>;
export declare function deleteAllMemoryOperation(deps: MemoryAdminDeps, input: DeleteAllMemoryInput): Promise<DeleteAllMemoryResult>;
export {};

@@ -0,1 +1,2 @@

import type { LanguageService } from "../language";
import type { Reranker } from "../recall/reranker";

@@ -23,12 +24,11 @@ import type { RecallRerankerTrace } from "../recall/retrievalTrace";

}): RecallRerankerTrace;
export declare function mergeDurableCandidateOrder(input: {
factIdsAfter: readonly string[];
factIdsBefore: readonly string[];
originalOrder: readonly string[];
}): string[];
export declare function applyFactRerankingToResult(input: {
export declare function getDurableRerankerCandidateCount(result: RecallResult): number;
export declare function applyDurableRerankingToResult(input: {
language: LanguageService;
preRankLimit?: number;
query: string;
reranker: Reranker;
result: RecallResult;
selectedLimit?: number;
target: RerankerExecutionTarget;
}): Promise<RecallResult>;

@@ -6,4 +6,4 @@ import type { GoodMemoryConfig, GoodMemoryExtractionProviderConfig, GoodMemoryRetrievalConfig, GoodMemoryRetrievalPresetId, GoodMemorySemanticCandidatesConfig } from "./contracts";

export declare const RECOMMENDED_GENERALIZED_FUSION_MAX_TOTAL_FACTS = 10;
export declare const RECOMMENDED_RERANK_GENERALIZED_FUSION_MAX_CANDIDATES = 20;
export declare const RECOMMENDED_RERANK_GENERALIZED_FUSION_MAX_TOTAL_FACTS = 20;
export declare const RECOMMENDED_RERANK_GENERALIZED_FUSION_MAX_CANDIDATES = 32;
export declare const RECOMMENDED_RERANK_GENERALIZED_FUSION_MAX_TOTAL_FACTS = 32;
export declare const HASHED_LEXICAL_EMBEDDING_BRAND: unique symbol;

@@ -10,0 +10,0 @@ export interface GoodMemoryRetrievalPresetStatus {

import type { GoodMemoryTracer } from "../observability/tracer";
import type { MemoryExtractionStrategy } from "../remember/candidates";
import type { LanguageService } from "../language";
import type { DocumentStore, SessionStore } from "../storage/contracts";
import type { GoodMemoryRuntimeFacade } from "./contracts";
import type { ScopeDeletionCoordinator } from "../storage/scopeDeletion";
import type { GoodMemoryRuntimeFacade, RememberInput, RememberResult } from "./contracts";
export interface GoodMemoryRuntimeFacadeConfig {
documentStore: DocumentStore;
language?: LanguageService;
scopeDeletion?: ScopeDeletionCoordinator;
sessionStore: SessionStore;
now: () => Date;
runtimeCompactionExtraction?: {
extractionStrategy: MemoryExtractionStrategy;
remember(input: RememberInput): Promise<RememberResult>;
};
tracer: GoodMemoryTracer;
}
export declare function createGoodMemoryRuntimeFacade(config: GoodMemoryRuntimeFacadeConfig): GoodMemoryRuntimeFacade;
#!/usr/bin/env bun
import{a as v}from"./chunk-eqzdmt9d.js";import{eb as O,gb as P,ma as R,na as c,oa as d,qa as F}from"./chunk-6set3gaz.js";import"./chunk-ve2dyh5j.js";import"./chunk-w0h24t3p.js";import"./chunk-xmaks7z1.js";import{resolve as y$}from"node:path";import{fileURLToPath as c$}from"node:url";var D="phase-39.http-memory.v1",_$=new Set(["export","forget","revise"]);function _($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function W($){return typeof $==="string"&&$.trim().length>0}function V($,X){let Z=$[X];if(Z===void 0)return;return W(Z)?Z.trim():void 0}function G$($){if(!_($)||!W($.userId))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};for(let j of["tenantId","workspaceId","agentId","sessionId"])if($[j]!==void 0&&!W($[j]))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};let X={userId:$.userId.trim()},Z=V($,"tenantId"),U=V($,"workspaceId"),Q=V($,"agentId"),Y=V($,"sessionId");if(Z)X.tenantId=Z;if(U)X.workspaceId=U;if(Q)X.agentId=Q;if(Y)X.sessionId=Y;return{ok:!0,value:X}}function D$($){if(!Array.isArray($)||$.length===0)return{code:"invalid_messages",message:"Expected messages to be a non-empty array.",ok:!1};let X=[];for(let Z of $){if(!_(Z)||!W(Z.role)||!W(Z.content))return{code:"invalid_messages",message:"Expected every message to include role and content string fields.",ok:!1};X.push({content:Z.content,role:Z.role})}return{ok:!0,value:X}}function x($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function L$($){return $==="profile"||$==="preference"||$==="reference"||$==="fact"||$==="feedback"}function M$($){return $==="always"||$==="never"||$==="auto"}function f($){return $==="blocker"||$==="open_loop"||$==="role_update"||$==="focus_update"||$==="project_state"||$==="generic_project"}function b($){return $==="identity"||$==="project"||$==="runtime"||$==="reference"||$==="preference"}function g($){return $==="do"||$==="dont"||$==="prefer"||$==="validated_pattern"}function m($){return $==="name"||$==="role"||$==="organization"||$==="location"||$==="timezone"||$==="languagePreference"||$==="currentProject"}function y($){return $==="source_of_truth"||$==="runbook"||$==="doc"||$==="dashboard"||$==="tracker"}function B$($){if($===void 0)return{ok:!0,value:void 0};if(!_($))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch to be an object when provided.",ok:!1};for(let Z of["category","factKind","scopeKind","subject","feedbackKind","appliesTo","profileField","preferenceCategory","preferenceValue","referenceKind","referenceTitle","referencePointer","supersedesPointer"])if($[Z]!==void 0&&!W($[Z]))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch string fields to be non-empty strings.",ok:!1};if($.factKind!==void 0&&!f($.factKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.factKind to be a supported fact kind.",ok:!1};if($.scopeKind!==void 0&&!b($.scopeKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.scopeKind to be a supported scope kind.",ok:!1};if($.feedbackKind!==void 0&&!g($.feedbackKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.feedbackKind to be a supported feedback kind.",ok:!1};if($.profileField!==void 0&&!m($.profileField))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.profileField to be a supported profile field.",ok:!1};if($.referenceKind!==void 0&&!y($.referenceKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.referenceKind to be a supported reference kind.",ok:!1};if($.tags!==void 0&&(!Array.isArray($.tags)||!$.tags.every(W)))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.tags to be an array of non-empty strings.",ok:!1};if($.attributes!==void 0){if(!_($.attributes))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes to be an object.",ok:!1};for(let Z of Object.values($.attributes))if(!x(Z))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes values to be string, number, boolean, or null.",ok:!1}}let X=_($.attributes)?Object.fromEntries(Object.entries($.attributes).filter((Z)=>x(Z[1]))):void 0;return{ok:!0,value:{...W($.category)?{category:$.category}:{},...f($.factKind)?{factKind:$.factKind}:{},...b($.scopeKind)?{scopeKind:$.scopeKind}:{},...W($.subject)?{subject:$.subject}:{},...Array.isArray($.tags)?{tags:[...$.tags]}:{},...X!==void 0?{attributes:X}:{},...g($.feedbackKind)?{feedbackKind:$.feedbackKind}:{},...W($.appliesTo)?{appliesTo:$.appliesTo}:{},...m($.profileField)?{profileField:$.profileField}:{},...W($.preferenceCategory)?{preferenceCategory:$.preferenceCategory}:{},...W($.preferenceValue)?{preferenceValue:$.preferenceValue}:{},...y($.referenceKind)?{referenceKind:$.referenceKind}:{},...W($.referenceTitle)?{referenceTitle:$.referenceTitle}:{},...W($.referencePointer)?{referencePointer:$.referencePointer}:{},...W($.supersedesPointer)?{supersedesPointer:$.supersedesPointer}:{}}}}function z$($){if($===void 0)return{ok:!0,value:void 0};if(!Array.isArray($))return{code:"invalid_annotations",message:"Expected annotations to be an array when provided.",ok:!1};let X=[];for(let Z of $){if(!_(Z))return{code:"invalid_annotations",message:"Expected every annotation to be an object.",ok:!1};let U=Z.messageIndex;if(typeof U!=="number"||!Number.isInteger(U))return{code:"invalid_annotations",message:"Expected every annotation to include integer messageIndex.",ok:!1};if(U<0)return{code:"invalid_annotations",message:"Expected annotation.messageIndex to be non-negative.",ok:!1};if(Z.remember!==void 0&&!M$(Z.remember))return{code:"invalid_annotations",message:"Expected annotation.remember to be always, never, or auto.",ok:!1};if(Z.kindHint!==void 0&&!L$(Z.kindHint))return{code:"invalid_annotations",message:"Expected annotation.kindHint to be profile, preference, reference, fact, or feedback.",ok:!1};if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.confirmed to be a boolean when provided.",ok:!1};if(Z.verified!==void 0&&typeof Z.verified!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.verified to be a boolean when provided.",ok:!1};if(Z.reason!==void 0&&!W(Z.reason))return{code:"invalid_annotations",message:"Expected annotation.reason to be a non-empty string when provided.",ok:!1};let Q=B$(Z.metadataPatch);if(!Q.ok)return Q;X.push({messageIndex:U,...Z.remember!==void 0?{remember:Z.remember}:{},...Z.kindHint!==void 0?{kindHint:Z.kindHint}:{},...Q.value!==void 0?{metadataPatch:Q.value}:{},...Z.confirmed!==void 0?{confirmed:Z.confirmed}:{},...Z.verified!==void 0?{verified:Z.verified}:{},...W(Z.reason)?{reason:Z.reason}:{}})}return{ok:!0,value:X}}function F$($){if($===void 0)return{ok:!0,value:void 0};if($==="coding_agent"||$==="general_chat")return{ok:!0,value:$};return{code:"invalid_retrieval_profile",message:"Expected retrievalProfile to be general_chat or coding_agent.",ok:!1}}function w$($){if($===void 0)return{ok:!0,value:void 0};if($==="auto"||$==="rules-only"||$==="hybrid")return{ok:!0,value:$};return{code:"invalid_recall_strategy",message:"Expected strategy to be auto, rules-only, or hybrid.",ok:!1}}function O$($){if($===void 0)return{ok:!0,value:"system_prompt_fragment"};if($==="json"||$==="markdown"||$==="system_prompt_fragment"||$==="developer_prompt_fragment")return{ok:!0,value:$};return{code:"invalid_context_output",message:"Expected output to be json, markdown, system_prompt_fragment, or developer_prompt_fragment.",ok:!1}}function K$($){if($===void 0)return{ok:!0,value:void 0};if($==="auto"||$==="rules-only"||$==="llm-assisted")return{ok:!0,value:$};return{code:"invalid_extraction_strategy",message:"Expected extractionStrategy to be auto, rules-only, or llm-assisted.",ok:!1}}function C($,X){if($===void 0&&!X)return{ok:!0,value:void 0};if(W($))return{ok:!0,value:$.trim()};return{code:"invalid_idempotency_key",message:"Expected a non-empty idempotencyKey string.",ok:!1}}function V$($){if($===void 0)return{ok:!0,value:void 0};if(!_($))return{code:"invalid_evidence",message:"Expected evidence to be an object when provided.",ok:!1};if($.source!=="user_message"&&$.source!=="manual_review"&&$.source!=="system")return{code:"invalid_evidence",message:"Expected evidence.source to be user_message, manual_review, or system.",ok:!1};return{ok:!0,value:{source:$.source,...W($.message)?{message:$.message}:{},...W($.excerpt)?{excerpt:$.excerpt}:{},...W($.sourceUri)?{sourceUri:$.sourceUri}:{},...Array.isArray($.sourceMessageIds)?{sourceMessageIds:$.sourceMessageIds.filter(W)}:{}}}}function T$($,X){return{error:{code:$,message:X},ok:!1}}function L($,X){return{body:X,statusCode:$}}function H($,X,Z){return L($,T$(X,Z))}async function P$($){try{let X=await $.json();if(!_(X))return{code:"invalid_json_body",message:"Expected a JSON object request body.",ok:!1};return{ok:!0,value:X}}catch{return{code:"invalid_json_body",message:"Expected a valid JSON object request body.",ok:!1}}}function R$($){let X=$.headers.get("x-goodmemory-user-id")?.trim();if(!X)return null;let U=$.headers.get("x-goodmemory-operations")?.split(",").map((Q)=>Q.trim()).filter(Boolean);return{authorizedOperations:U?.includes("*")?"*":U??[],tenantId:$.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:X,workspaceId:$.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function C$($){if(!$.caller)return{authorized:!1,code:"caller_required",message:"The bridge requires a backend-resolved caller identity.",statusCode:401};if($.caller.userId!==$.scope.userId)return{authorized:!1,code:"scope_not_authorized",message:"Caller userId must match scope.userId.",statusCode:403};if($.caller.tenantId&&$.scope.tenantId!==$.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.tenantId must be present and match the caller tenantId.",statusCode:403};if($.scope.tenantId&&!$.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide tenantId to authorize tenant-scoped memory.",statusCode:403};if($.caller.workspaceId&&$.scope.workspaceId!==$.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.workspaceId must be present and match the caller workspaceId.",statusCode:403};if($.scope.workspaceId&&!$.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide workspaceId to authorize workspace-scoped memory.",statusCode:403};if($.sensitive&&$.caller.authorizedOperations!=="*"){if(!$.caller.authorizedOperations.includes($.operation))return{authorized:!1,code:"operation_not_authorized",message:"Caller is not authorized for this scoped memory operation.",statusCode:403}}return{authorized:!0}}function A$($){if(typeof $==="string")return $;return JSON.stringify($)}function B($,X){if(!X||X.content.trim().length===0)return;$.push(X)}function N$($){return Boolean($.profile||$.preferences.length>0||$.references.length>0||$.facts.length>0||$.feedback.length>0||$.archives.length>0||$.episodes.length>0||$.workingMemory||$.journal)}function p($,X=[]){let Z=$.metadata.routingDecision.strategyExplanation,U=new Set([...Z.warnings??[],...X]);if($.metadata.policyApplied?.includes("semantic_candidates_unavailable"))U.add(R);let Q=c({existingMessages:Z.warningMessages,warnings:[...U]});return{...Z.fallbackReason?{fallbackReason:Z.fallbackReason}:{},llmRefinement:Z.llmRefinement,requestedStrategy:Z.requestedStrategy,resolvedStrategy:Z.resolvedStrategy,semanticTieBreaking:Z.semanticTieBreaking,...Q.length>0?{warningMessages:Q}:{},...U.size>0?{warnings:[...U]}:{}}}function q$($){if($.requestedStrategy!=="auto"||$.runtimeInfo?.embeddingEnabled!==!0||$.runtimeInfo.retrievalPreset)return[];return($.recall.metadata.routingDecision.strategyExplanation.resolvedStrategy??$.recall.metadata.routingDecision.strategy)==="rules-only"?[R]:[]}function I$($){return{...p($.recall),fallbackReason:"provider_error",providerFallback:{reason:"provider_error",recoveredStrategy:"rules-only"},requestedStrategy:$.requestedStrategy,resolvedStrategy:"rules-only",semanticTieBreaking:!1}}function E$($){let X=[];if($.profile){let Z=[$.profile.identity.name,$.profile.identity.role,$.profile.identity.organization,...$.profile.activeContext.goals,...$.profile.activeContext.currentProjects].filter(W);B(X,{content:Z.join("; "),memoryId:`profile:${$.profile.userId}`,source:"goodmemory",type:"profile"})}for(let Z of $.preferences)B(X,{category:Z.category,confidence:Z.confidence,content:`${Z.category}: ${A$(Z.value)}`,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"preference"});for(let Z of $.references)B(X,{category:Z.referenceKind,confidence:Z.confidence,content:Z.description?`${Z.title}: ${Z.pointer} - ${Z.description}`:`${Z.title}: ${Z.pointer}`,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"reference"});for(let Z of $.facts)B(X,{category:Z.category,confidence:Z.confidence,content:Z.content,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"fact"});for(let Z of $.feedback)B(X,{category:Z.kind,confidence:Z.confidence,content:Z.rule,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"feedback"});for(let Z of $.episodes)B(X,{confidence:Z.confidence,content:Z.summary,memoryId:Z.id,source:"goodmemory",tags:Z.topics,type:"episode"});if($.workingMemory)B(X,{content:[$.workingMemory.currentGoal,...$.workingMemory.openLoops,...$.workingMemory.temporaryDecisions??[]].filter(W).join("; "),memoryId:`working-memory:${$.workingMemory.userId}:${$.workingMemory.sessionId}`,source:"goodmemory",type:"working_memory"});if($.journal)B(X,{content:[$.journal.currentState,$.journal.taskSpecification,...$.journal.workflow??[],...$.journal.errorsAndCorrections??[],...$.journal.learnings??[],...$.journal.keyResults??[],...$.journal.worklog].filter(W).join("; "),memoryId:`session-journal:${$.journal.userId}:${$.journal.sessionId}`,source:"goodmemory",type:"session_journal"});return X}async function S$($,X,Z){if(!W(X.query))return H(400,"invalid_query","Expected query to be a non-empty string.");let U=F$(X.retrievalProfile);if(!U.ok)return H(400,U.code,U.message);let Q=w$(X.strategy);if(!Q.ok)return H(400,Q.code,Q.message);let Y=O$(X.output);if(!Y.ok)return H(400,Y.code,Y.message);let j=typeof X.maxTokens==="number"&&Number.isFinite(X.maxTokens)?Math.max(1,Math.floor(X.maxTokens)):void 0,J=Q.value??"auto",G=O($),z=G?.retrievalPreset!==void 0?J:J==="hybrid"?"hybrid":"rules-only",I={scope:Z,query:X.query,...U.value?{retrievalProfile:U.value}:{},strategy:z},M,E=void 0;try{M=await $.recall(I)}catch(h){if(J==="rules-only"||!d(h))throw h;M=await $.recall({...I,strategy:"rules-only"}),E=I$({recall:M,requestedStrategy:J})}let w=await $.buildContext({recall:M,output:Y.value,...j?{maxTokens:j}:{}}),S=E$(M),k=w.traceId??M.metadata.traceId;return L(200,{context:{content:w.content,estimatedTokens:w.estimatedTokens,omittedSections:w.omittedSections,output:w.output},contextText:w.content,contractVersion:D,hasContext:N$(M),itemCount:S.length,items:S,ok:!0,operation:"recall-context",routing:E??{...p(M,q$({recall:M,requestedStrategy:J,runtimeInfo:G})),requestedStrategy:J},...k?{traceId:k}:{}})}async function k$($,X,Z){let U=D$(X.messages);if(!U.ok)return H(400,U.code,U.message);let Q=z$(X.annotations);if(!Q.ok)return H(400,Q.code,Q.message);let Y=K$(X.extractionStrategy);if(!Y.ok)return H(400,Y.code,Y.message);let j=X.mode===void 0?"sync":X.mode;if(j!=="sync"&&j!=="async")return H(400,"invalid_mode","Expected mode to be sync or async.");let J=C(X.idempotencyKey,j==="async");if(!J.ok)return H(400,J.code,J.message);let G={scope:Z,messages:U.value,...Q.value?{annotations:Q.value}:{},...Y.value?{extractionStrategy:Y.value}:{},...W(X.locale)?{locale:X.locale}:{}};if(j==="async")try{let z=await $.jobs.enqueueRemember({...G,idempotencyKey:J.value,reason:"manual_enqueue"});return L(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_jobs",key:J.value},job:z,mode:j,ok:!0,operation:"remember"})}catch(z){if(_(z)&&z.code==="idempotency_conflict")return H(409,"idempotency_conflict","GoodMemory job idempotency key already exists for a different payload.");throw z}let q=await $.remember(G);return L(200,{contractVersion:D,idempotency:J.value?{handledBy:"consumer_provenance_only",key:J.value}:{handledBy:"none"},mode:j,ok:!0,operation:"remember",result:q})}async function h$($,X,Z){if(!W(X.signal))return H(400,"invalid_signal","Expected signal to be a non-empty string.");let U=C(X.idempotencyKey,!0);if(!U.ok)return H(400,U.code,U.message);let Q=_(X.source)?X.source:{},Y=await $.feedback({scope:Z,signal:X.signal,...W(X.locale)?{locale:X.locale}:{}});return L(200,{contractVersion:D,idempotency:{handledBy:"consumer_provenance_only",key:U.value},ok:!0,operation:"feedback",provenance:{...W(Q.eventId)?{eventId:Q.eventId}:{},...W(Q.proposalId)?{proposalId:Q.proposalId}:{},...W(Q.reason)?{reason:Q.reason}:{},...W(Q.reviewDecision)?{reviewDecision:Q.reviewDecision}:{},...W(Q.system)?{system:Q.system}:{}},result:Y})}async function x$($,X,Z){if(!W(X.memoryId))return H(400,"invalid_memory_id","Expected memoryId to be a non-empty string.");let U=await $.forget({memoryId:X.memoryId,scope:Z});return L(200,{contractVersion:D,ok:!0,operation:"forget",result:U})}async function f$($,X,Z){let U=X.includeRuntime===!0,Q=await $.exportMemory({includeRuntime:U,scope:Z});return L(200,{contractVersion:D,exported:Q,includeRuntime:U,ok:!0,operation:"export"})}async function b$($,X,Z){let U=_(X.target)?X.target:null;if(!U||!W(U.memoryId))return H(400,"target_memory_id_required","Expected target.memoryId. Query-resolved revision targets are out of scope.");if(!_(X.revision)||!W(X.revision.content))return H(400,"invalid_revision","Expected revision.content to be a non-empty string.");if(!W(X.reason))return H(400,"invalid_reason","Expected reason to be a non-empty string.");let Q=C(X.idempotencyKey,!0);if(!Q.ok)return H(400,Q.code,Q.message);let Y=Q.value;if(!Y)return H(400,"invalid_idempotency_key","Expected a non-empty idempotencyKey string.");let j=V$(X.evidence);if(!j.ok)return H(400,j.code,j.message);let J=await $.reviseMemory({evidence:j.value,idempotencyKey:Y,reason:X.reason,revision:{content:X.revision.content},scope:Z,target:{memoryId:U.memoryId}});return L(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_revision",key:Y},ok:!0,operation:"revise",result:J})}function g$($){if($==="/memory/recall-context")return"recall-context";if($==="/memory/remember")return"remember";if($==="/memory/feedback")return"feedback";if($==="/memory/forget")return"forget";if($==="/memory/export")return"export";if($==="/memory/revise")return"revise";return null}async function m$($){if($.operation==="recall-context")return S$($.memory,$.body,$.scope);if($.operation==="remember")return k$($.memory,$.body,$.scope);if($.operation==="feedback")return h$($.memory,$.body,$.scope);if($.operation==="forget")return x$($.memory,$.body,$.scope);if($.operation==="export")return f$($.memory,$.body,$.scope);return b$($.memory,$.body,$.scope)}function s($){let X=$.resolveCaller??R$,Z=$.authorize??C$;async function U(Q){if(Q.method==="GET"&&new URL(Q.url).pathname==="/healthz")return L(200,{...$.healthMetadata??{},contractVersion:D,ok:!0,status:"ok"});if(Q.method==="GET"&&new URL(Q.url).pathname==="/.well-known/goodmemory.json")return L(200,v());if(Q.method!=="POST")return H(405,"method_not_allowed","GoodMemory bridge endpoints require POST.");let Y=g$(new URL(Q.url).pathname);if(!Y)return H(404,"not_found","Unknown GoodMemory bridge endpoint.");let j=await P$(Q);if(!j.ok)return H(400,j.code,j.message);let J=G$(j.value.scope);if(!J.ok)return H(400,J.code,J.message);let G=await Z({body:j.value,caller:X(Q,j.value),operation:Y,request:Q,scope:J.value,sensitive:_$.has(Y)});if(!G.authorized)return H(G.statusCode??403,G.code??"operation_not_authorized",G.message??"Caller is not authorized for this memory operation.");try{return await m$({body:j.value,memory:$.memory,operation:Y,scope:J.value})}catch{return H(500,"bridge_operation_failed","GoodMemory bridge operation failed.")}}return{async fetch(Q){let Y=await U(Q);return new Response(JSON.stringify(Y.body),{headers:{"content-type":"application/json"},status:Y.statusCode})},handle:U}}function u(){return{preset:"default",profiles:[{assistantOutputs:{mode:"confirmed_or_verified_only"},extends:"default",id:"life-coach",rules:[F.fact(/my top priority this quarter is (.+)/i,{category:"goal",content:({match:$})=>`Quarterly priority: ${$[1]??""}`,id:"life-coach-quarterly-priority",tags:["life_coach","goal"]}),F.fact(/my current goal is (.+)/i,{category:"goal",content:({match:$})=>$[1]??"",id:"life-coach-current-goal",tags:["life_coach","goal"]}),F.fact(/my habit is (.+)/i,{category:"habit",content:({match:$})=>$[1]??"",id:"life-coach-habit",tags:["life_coach","habit"]}),F.preference(/please coach me with (.+)/i,{category:"coaching_style",id:"life-coach-coaching-style",tags:["life_coach","coaching_style"],value:({match:$})=>$[1]??""}),F.feedback(/keep doing (.+)/i,{appliesTo:"life_coach_response",content:({match:$})=>$[1]??"",feedbackKind:"do",id:"life-coach-intervention-feedback",tags:["life_coach","intervention_feedback"]})],when:{agentId:"life-coach"}}]}}var t="127.0.0.1",e=8739,$$="GOODMEMORY_HTTP_BRIDGE_HOST",X$="GOODMEMORY_HTTP_BRIDGE_PORT",A="GOODMEMORY_HTTP_BRIDGE_TOKEN",N="GOODMEMORY_HTTP_BRIDGE_AUTH",Z$="x-goodmemory-bridge-auth",Q$="GOODMEMORY_HTTP_BRIDGE_PROFILE",U$="GOODMEMORY_HTTP_BRIDGE_RETRIEVAL_PRESET",W$="GOODMEMORY_HTTP_BRIDGE_RECOMMENDED",Y$="GOODMEMORY_PROFILE",j$="GOODMEMORY_HTTP_BRIDGE_ALLOW_INSECURE";function d$(){console.log(`GoodMemory HTTP memory bridge
import{a as d}from"./chunk-c8pcftxd.js";import{Ja as w,La as T,ta as P,ua as y,va as c}from"./chunk-c5jbqdf4.js";import"./chunk-wy6fj8p6.js";import{resolve as y$}from"node:path";import{fileURLToPath as c$}from"node:url";var G="phase-39.http-memory.v1",_$=new Set(["export","forget","revise"]);function _($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function W($){return typeof $==="string"&&$.trim().length>0}function K($,X){let Z=$[X];if(Z===void 0)return;return W(Z)?Z.trim():void 0}function D$($){if(!_($)||!W($.userId))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};for(let j of["tenantId","workspaceId","agentId","sessionId"])if($[j]!==void 0&&!W($[j]))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};let X={userId:$.userId.trim()},Z=K($,"tenantId"),U=K($,"workspaceId"),Q=K($,"agentId"),Y=K($,"sessionId");if(Z)X.tenantId=Z;if(U)X.workspaceId=U;if(Q)X.agentId=Q;if(Y)X.sessionId=Y;return{ok:!0,value:X}}function G$($){if(!Array.isArray($)||$.length===0)return{code:"invalid_messages",message:"Expected messages to be a non-empty array.",ok:!1};let X=[];for(let Z of $){if(!_(Z)||!W(Z.role)||!W(Z.content))return{code:"invalid_messages",message:"Expected every message to include role and content string fields.",ok:!1};X.push({content:Z.content,role:Z.role})}return{ok:!0,value:X}}function h($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function L$($){return $==="profile"||$==="preference"||$==="reference"||$==="fact"||$==="feedback"}function B$($){return $==="always"||$==="never"||$==="auto"}function x($){return $==="blocker"||$==="open_loop"||$==="role_update"||$==="focus_update"||$==="project_state"||$==="generic_project"}function f($){return $==="identity"||$==="project"||$==="runtime"||$==="reference"||$==="preference"}function b($){return $==="do"||$==="dont"||$==="prefer"||$==="validated_pattern"}function g($){return $==="name"||$==="role"||$==="organization"||$==="location"||$==="timezone"||$==="languagePreference"||$==="currentProject"}function m($){return $==="source_of_truth"||$==="runbook"||$==="doc"||$==="dashboard"||$==="tracker"}function M$($){if($===void 0)return{ok:!0,value:void 0};if(!_($))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch to be an object when provided.",ok:!1};for(let Z of["category","factKind","scopeKind","subject","feedbackKind","appliesTo","profileField","preferenceCategory","preferenceValue","referenceKind","referenceTitle","referencePointer","supersedesPointer"])if($[Z]!==void 0&&!W($[Z]))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch string fields to be non-empty strings.",ok:!1};if($.factKind!==void 0&&!x($.factKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.factKind to be a supported fact kind.",ok:!1};if($.scopeKind!==void 0&&!f($.scopeKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.scopeKind to be a supported scope kind.",ok:!1};if($.feedbackKind!==void 0&&!b($.feedbackKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.feedbackKind to be a supported feedback kind.",ok:!1};if($.profileField!==void 0&&!g($.profileField))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.profileField to be a supported profile field.",ok:!1};if($.referenceKind!==void 0&&!m($.referenceKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.referenceKind to be a supported reference kind.",ok:!1};if($.tags!==void 0&&(!Array.isArray($.tags)||!$.tags.every(W)))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.tags to be an array of non-empty strings.",ok:!1};if($.attributes!==void 0){if(!_($.attributes))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes to be an object.",ok:!1};for(let Z of Object.values($.attributes))if(!h(Z))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes values to be string, number, boolean, or null.",ok:!1}}let X=_($.attributes)?Object.fromEntries(Object.entries($.attributes).filter((Z)=>h(Z[1]))):void 0;return{ok:!0,value:{...W($.category)?{category:$.category}:{},...x($.factKind)?{factKind:$.factKind}:{},...f($.scopeKind)?{scopeKind:$.scopeKind}:{},...W($.subject)?{subject:$.subject}:{},...Array.isArray($.tags)?{tags:[...$.tags]}:{},...X!==void 0?{attributes:X}:{},...b($.feedbackKind)?{feedbackKind:$.feedbackKind}:{},...W($.appliesTo)?{appliesTo:$.appliesTo}:{},...g($.profileField)?{profileField:$.profileField}:{},...W($.preferenceCategory)?{preferenceCategory:$.preferenceCategory}:{},...W($.preferenceValue)?{preferenceValue:$.preferenceValue}:{},...m($.referenceKind)?{referenceKind:$.referenceKind}:{},...W($.referenceTitle)?{referenceTitle:$.referenceTitle}:{},...W($.referencePointer)?{referencePointer:$.referencePointer}:{},...W($.supersedesPointer)?{supersedesPointer:$.supersedesPointer}:{}}}}function z$($){if($===void 0)return{ok:!0,value:void 0};if(!Array.isArray($))return{code:"invalid_annotations",message:"Expected annotations to be an array when provided.",ok:!1};let X=[];for(let Z of $){if(!_(Z))return{code:"invalid_annotations",message:"Expected every annotation to be an object.",ok:!1};let U=Z.messageIndex;if(typeof U!=="number"||!Number.isInteger(U))return{code:"invalid_annotations",message:"Expected every annotation to include integer messageIndex.",ok:!1};if(U<0)return{code:"invalid_annotations",message:"Expected annotation.messageIndex to be non-negative.",ok:!1};if(Z.remember!==void 0&&!B$(Z.remember))return{code:"invalid_annotations",message:"Expected annotation.remember to be always, never, or auto.",ok:!1};if(Z.kindHint!==void 0&&!L$(Z.kindHint))return{code:"invalid_annotations",message:"Expected annotation.kindHint to be profile, preference, reference, fact, or feedback.",ok:!1};if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.confirmed to be a boolean when provided.",ok:!1};if(Z.verified!==void 0&&typeof Z.verified!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.verified to be a boolean when provided.",ok:!1};if(Z.reason!==void 0&&!W(Z.reason))return{code:"invalid_annotations",message:"Expected annotation.reason to be a non-empty string when provided.",ok:!1};let Q=M$(Z.metadataPatch);if(!Q.ok)return Q;X.push({messageIndex:U,...Z.remember!==void 0?{remember:Z.remember}:{},...Z.kindHint!==void 0?{kindHint:Z.kindHint}:{},...Q.value!==void 0?{metadataPatch:Q.value}:{},...Z.confirmed!==void 0?{confirmed:Z.confirmed}:{},...Z.verified!==void 0?{verified:Z.verified}:{},...W(Z.reason)?{reason:Z.reason}:{}})}return{ok:!0,value:X}}function F$($){if($===void 0)return{ok:!0,value:void 0};if($==="coding_agent"||$==="general_chat")return{ok:!0,value:$};return{code:"invalid_retrieval_profile",message:"Expected retrievalProfile to be general_chat or coding_agent.",ok:!1}}function w$($){if($===void 0)return{ok:!0,value:void 0};if($==="auto"||$==="rules-only"||$==="hybrid")return{ok:!0,value:$};return{code:"invalid_recall_strategy",message:"Expected strategy to be auto, rules-only, or hybrid.",ok:!1}}function O$($){if($===void 0)return{ok:!0,value:"system_prompt_fragment"};if($==="json"||$==="markdown"||$==="system_prompt_fragment"||$==="developer_prompt_fragment")return{ok:!0,value:$};return{code:"invalid_context_output",message:"Expected output to be json, markdown, system_prompt_fragment, or developer_prompt_fragment.",ok:!1}}function K$($){if($===void 0)return{ok:!0,value:void 0};if($==="auto"||$==="rules-only"||$==="llm-assisted")return{ok:!0,value:$};return{code:"invalid_extraction_strategy",message:"Expected extractionStrategy to be auto, rules-only, or llm-assisted.",ok:!1}}function R($,X){if($===void 0&&!X)return{ok:!0,value:void 0};if(W($))return{ok:!0,value:$.trim()};return{code:"invalid_idempotency_key",message:"Expected a non-empty idempotencyKey string.",ok:!1}}function V$($){if($===void 0)return{ok:!0,value:void 0};if(!_($))return{code:"invalid_evidence",message:"Expected evidence to be an object when provided.",ok:!1};if($.source!=="user_message"&&$.source!=="manual_review"&&$.source!=="system")return{code:"invalid_evidence",message:"Expected evidence.source to be user_message, manual_review, or system.",ok:!1};return{ok:!0,value:{source:$.source,...W($.message)?{message:$.message}:{},...W($.excerpt)?{excerpt:$.excerpt}:{},...W($.sourceUri)?{sourceUri:$.sourceUri}:{},...Array.isArray($.sourceMessageIds)?{sourceMessageIds:$.sourceMessageIds.filter(W)}:{}}}}function T$($,X){return{error:{code:$,message:X},ok:!1}}function L($,X){return{body:X,statusCode:$}}function H($,X,Z){return L($,T$(X,Z))}async function P$($){try{let X=await $.json();if(!_(X))return{code:"invalid_json_body",message:"Expected a JSON object request body.",ok:!1};return{ok:!0,value:X}}catch{return{code:"invalid_json_body",message:"Expected a valid JSON object request body.",ok:!1}}}function R$($){let X=$.headers.get("x-goodmemory-user-id")?.trim();if(!X)return null;let U=$.headers.get("x-goodmemory-operations")?.split(",").map((Q)=>Q.trim()).filter(Boolean);return{authorizedOperations:U?.includes("*")?"*":U??[],tenantId:$.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:X,workspaceId:$.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function C$($){if(!$.caller)return{authorized:!1,code:"caller_required",message:"The bridge requires a backend-resolved caller identity.",statusCode:401};if($.caller.userId!==$.scope.userId)return{authorized:!1,code:"scope_not_authorized",message:"Caller userId must match scope.userId.",statusCode:403};if($.caller.tenantId&&$.scope.tenantId!==$.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.tenantId must be present and match the caller tenantId.",statusCode:403};if($.scope.tenantId&&!$.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide tenantId to authorize tenant-scoped memory.",statusCode:403};if($.caller.workspaceId&&$.scope.workspaceId!==$.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.workspaceId must be present and match the caller workspaceId.",statusCode:403};if($.scope.workspaceId&&!$.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide workspaceId to authorize workspace-scoped memory.",statusCode:403};if($.sensitive&&$.caller.authorizedOperations!=="*"){if(!$.caller.authorizedOperations.includes($.operation))return{authorized:!1,code:"operation_not_authorized",message:"Caller is not authorized for this scoped memory operation.",statusCode:403}}return{authorized:!0}}function A$($){if(typeof $==="string")return $;return JSON.stringify($)}function M($,X){if(!X||X.content.trim().length===0)return;$.push(X)}function N$($){return Boolean($.profile||$.preferences.length>0||$.references.length>0||$.facts.length>0||$.feedback.length>0||$.archives.length>0||$.episodes.length>0||$.workingMemory||$.journal)}function v($,X=[]){let Z=$.metadata.routingDecision.strategyExplanation,U=new Set([...Z.warnings??[],...X]);if($.metadata.policyApplied?.includes("semantic_candidates_unavailable"))U.add(P);let Q=y({existingMessages:Z.warningMessages,warnings:[...U]});return{...Z.fallbackReason?{fallbackReason:Z.fallbackReason}:{},llmRefinement:Z.llmRefinement,requestedStrategy:Z.requestedStrategy,resolvedStrategy:Z.resolvedStrategy,semanticTieBreaking:Z.semanticTieBreaking,...Q.length>0?{warningMessages:Q}:{},...U.size>0?{warnings:[...U]}:{}}}function q$($){if($.requestedStrategy!=="auto"||$.runtimeInfo?.embeddingEnabled!==!0||$.runtimeInfo.retrievalPreset)return[];return($.recall.metadata.routingDecision.strategyExplanation.resolvedStrategy??$.recall.metadata.routingDecision.strategy)==="rules-only"?[P]:[]}function I$($){return{...v($.recall),fallbackReason:"provider_error",providerFallback:{reason:"provider_error",recoveredStrategy:"rules-only"},requestedStrategy:$.requestedStrategy,resolvedStrategy:"rules-only",semanticTieBreaking:!1}}function E$($){let X=[];if($.profile){let Z=[$.profile.identity.name,$.profile.identity.role,$.profile.identity.organization,...$.profile.activeContext.goals,...$.profile.activeContext.currentProjects].filter(W);M(X,{content:Z.join("; "),memoryId:`profile:${$.profile.userId}`,source:"goodmemory",type:"profile"})}for(let Z of $.preferences)M(X,{category:Z.category,confidence:Z.confidence,content:`${Z.category}: ${A$(Z.value)}`,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"preference"});for(let Z of $.references)M(X,{category:Z.referenceKind,confidence:Z.confidence,content:Z.description?`${Z.title}: ${Z.pointer} - ${Z.description}`:`${Z.title}: ${Z.pointer}`,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"reference"});for(let Z of $.facts)M(X,{category:Z.category,confidence:Z.confidence,content:Z.content,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"fact"});for(let Z of $.feedback)M(X,{category:Z.kind,confidence:Z.confidence,content:Z.rule,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"feedback"});for(let Z of $.episodes)M(X,{confidence:Z.confidence,content:Z.summary,memoryId:Z.id,source:"goodmemory",tags:Z.topics,type:"episode"});if($.workingMemory)M(X,{content:[$.workingMemory.currentGoal,...$.workingMemory.openLoops,...$.workingMemory.temporaryDecisions??[]].filter(W).join("; "),memoryId:`working-memory:${$.workingMemory.userId}:${$.workingMemory.sessionId}`,source:"goodmemory",type:"working_memory"});if($.journal)M(X,{content:[$.journal.currentState,$.journal.taskSpecification,...$.journal.workflow??[],...$.journal.errorsAndCorrections??[],...$.journal.learnings??[],...$.journal.keyResults??[],...$.journal.worklog].filter(W).join("; "),memoryId:`session-journal:${$.journal.userId}:${$.journal.sessionId}`,source:"goodmemory",type:"session_journal"});return X}async function S$($,X,Z){if(!W(X.query))return H(400,"invalid_query","Expected query to be a non-empty string.");let U=F$(X.retrievalProfile);if(!U.ok)return H(400,U.code,U.message);let Q=w$(X.strategy);if(!Q.ok)return H(400,Q.code,Q.message);let Y=O$(X.output);if(!Y.ok)return H(400,Y.code,Y.message);let j=typeof X.maxTokens==="number"&&Number.isFinite(X.maxTokens)?Math.max(1,Math.floor(X.maxTokens)):void 0,J=Q.value??"auto",D=w($),z=D?.retrievalPreset!==void 0?J:J==="hybrid"?"hybrid":"rules-only",q={scope:Z,query:X.query,...U.value?{retrievalProfile:U.value}:{},strategy:z},B,I=void 0;try{B=await $.recall(q)}catch(k){if(J==="rules-only"||!c(k))throw k;B=await $.recall({...q,strategy:"rules-only"}),I=I$({recall:B,requestedStrategy:J})}let F=await $.buildContext({recall:B,output:Y.value,...j?{maxTokens:j}:{}}),E=E$(B),S=F.traceId??B.metadata.traceId;return L(200,{context:{content:F.content,estimatedTokens:F.estimatedTokens,omittedSections:F.omittedSections,output:F.output},contextText:F.content,contractVersion:G,hasContext:N$(B),itemCount:E.length,items:E,ok:!0,operation:"recall-context",routing:I??{...v(B,q$({recall:B,requestedStrategy:J,runtimeInfo:D})),requestedStrategy:J},...S?{traceId:S}:{}})}async function k$($,X,Z){let U=G$(X.messages);if(!U.ok)return H(400,U.code,U.message);let Q=z$(X.annotations);if(!Q.ok)return H(400,Q.code,Q.message);let Y=K$(X.extractionStrategy);if(!Y.ok)return H(400,Y.code,Y.message);let j=X.mode===void 0?"sync":X.mode;if(j!=="sync"&&j!=="async")return H(400,"invalid_mode","Expected mode to be sync or async.");let J=R(X.idempotencyKey,j==="async");if(!J.ok)return H(400,J.code,J.message);let D={scope:Z,messages:U.value,...Q.value?{annotations:Q.value}:{},...Y.value?{extractionStrategy:Y.value}:{},...W(X.locale)?{locale:X.locale}:{}};if(j==="async")try{let z=await $.jobs.enqueueRemember({...D,idempotencyKey:J.value,reason:"manual_enqueue"});return L(200,{contractVersion:G,idempotency:{handledBy:"goodmemory_jobs",key:J.value},job:z,mode:j,ok:!0,operation:"remember"})}catch(z){if(_(z)&&z.code==="idempotency_conflict")return H(409,"idempotency_conflict","GoodMemory job idempotency key already exists for a different payload.");throw z}let N=await $.remember(D);return L(200,{contractVersion:G,idempotency:J.value?{handledBy:"consumer_provenance_only",key:J.value}:{handledBy:"none"},mode:j,ok:!0,operation:"remember",result:N})}async function h$($,X,Z){if(!W(X.signal))return H(400,"invalid_signal","Expected signal to be a non-empty string.");let U=R(X.idempotencyKey,!0);if(!U.ok)return H(400,U.code,U.message);let Q=_(X.source)?X.source:{},Y=await $.feedback({scope:Z,signal:X.signal,...W(X.locale)?{locale:X.locale}:{}});return L(200,{contractVersion:G,idempotency:{handledBy:"consumer_provenance_only",key:U.value},ok:!0,operation:"feedback",provenance:{...W(Q.eventId)?{eventId:Q.eventId}:{},...W(Q.proposalId)?{proposalId:Q.proposalId}:{},...W(Q.reason)?{reason:Q.reason}:{},...W(Q.reviewDecision)?{reviewDecision:Q.reviewDecision}:{},...W(Q.system)?{system:Q.system}:{}},result:Y})}async function x$($,X,Z){if(!W(X.memoryId))return H(400,"invalid_memory_id","Expected memoryId to be a non-empty string.");let U=await $.forget({memoryId:X.memoryId,scope:Z});return L(200,{contractVersion:G,ok:!0,operation:"forget",result:U})}async function f$($,X,Z){let U=X.includeRuntime===!0,Q=await $.exportMemory({includeRuntime:U,scope:Z});return L(200,{contractVersion:G,exported:Q,includeRuntime:U,ok:!0,operation:"export"})}async function b$($,X,Z){let U=_(X.target)?X.target:null;if(!U||!W(U.memoryId))return H(400,"target_memory_id_required","Expected target.memoryId. Query-resolved revision targets are out of scope.");if(!_(X.revision)||!W(X.revision.content))return H(400,"invalid_revision","Expected revision.content to be a non-empty string.");if(!W(X.reason))return H(400,"invalid_reason","Expected reason to be a non-empty string.");let Q=R(X.idempotencyKey,!0);if(!Q.ok)return H(400,Q.code,Q.message);let Y=Q.value;if(!Y)return H(400,"invalid_idempotency_key","Expected a non-empty idempotencyKey string.");let j=V$(X.evidence);if(!j.ok)return H(400,j.code,j.message);let J=await $.reviseMemory({evidence:j.value,idempotencyKey:Y,reason:X.reason,revision:{content:X.revision.content},scope:Z,target:{memoryId:U.memoryId}});return L(200,{contractVersion:G,idempotency:{handledBy:"goodmemory_revision",key:Y},ok:!0,operation:"revise",result:J})}function g$($){if($==="/memory/recall-context")return"recall-context";if($==="/memory/remember")return"remember";if($==="/memory/feedback")return"feedback";if($==="/memory/forget")return"forget";if($==="/memory/export")return"export";if($==="/memory/revise")return"revise";return null}async function m$($){if($.operation==="recall-context")return S$($.memory,$.body,$.scope);if($.operation==="remember")return k$($.memory,$.body,$.scope);if($.operation==="feedback")return h$($.memory,$.body,$.scope);if($.operation==="forget")return x$($.memory,$.body,$.scope);if($.operation==="export")return f$($.memory,$.body,$.scope);return b$($.memory,$.body,$.scope)}function p($){let X=$.resolveCaller??R$,Z=$.authorize??C$;async function U(Q){if(Q.method==="GET"&&new URL(Q.url).pathname==="/healthz")return L(200,{...$.healthMetadata??{},contractVersion:G,ok:!0,status:"ok"});if(Q.method==="GET"&&new URL(Q.url).pathname==="/.well-known/goodmemory.json")return L(200,d());if(Q.method!=="POST")return H(405,"method_not_allowed","GoodMemory bridge endpoints require POST.");let Y=g$(new URL(Q.url).pathname);if(!Y)return H(404,"not_found","Unknown GoodMemory bridge endpoint.");let j=await P$(Q);if(!j.ok)return H(400,j.code,j.message);let J=D$(j.value.scope);if(!J.ok)return H(400,J.code,J.message);let D=await Z({body:j.value,caller:X(Q,j.value),operation:Y,request:Q,scope:J.value,sensitive:_$.has(Y)});if(!D.authorized)return H(D.statusCode??403,D.code??"operation_not_authorized",D.message??"Caller is not authorized for this memory operation.");try{return await m$({body:j.value,memory:$.memory,operation:Y,scope:J.value})}catch{return H(500,"bridge_operation_failed","GoodMemory bridge operation failed.")}}return{async fetch(Q){let Y=await U(Q);return new Response(JSON.stringify(Y.body),{headers:{"content-type":"application/json"},status:Y.statusCode})},handle:U}}function s(){return{preset:"default",profiles:[{assistantOutputs:{mode:"confirmed_or_verified_only"},extends:"default",id:"life-coach",when:{agentId:"life-coach"}}]}}var a="127.0.0.1",t=8739,e="GOODMEMORY_HTTP_BRIDGE_HOST",$$="GOODMEMORY_HTTP_BRIDGE_PORT",C="GOODMEMORY_HTTP_BRIDGE_TOKEN",A="GOODMEMORY_HTTP_BRIDGE_AUTH",X$="x-goodmemory-bridge-auth",Z$="GOODMEMORY_HTTP_BRIDGE_PROFILE",Q$="GOODMEMORY_HTTP_BRIDGE_RETRIEVAL_PRESET",U$="GOODMEMORY_HTTP_BRIDGE_RECOMMENDED",W$="GOODMEMORY_PROFILE",Y$="GOODMEMORY_HTTP_BRIDGE_ALLOW_INSECURE";function d$(){console.log(`GoodMemory HTTP memory bridge

@@ -15,14 +15,14 @@ Usage:

Environment:
${A} Bearer token required by default
${N} Bearer token alias for hosts that reserve TOKEN variable names
${$$} Hostname, defaults to ${t}
${X$} Port, defaults to ${e}
${Q$} default or life-coach
${Y$}=agent-recommended
${C} Bearer token required by default
${A} Bearer token alias for hosts that reserve TOKEN variable names
${e} Hostname, defaults to ${a}
${$$} Port, defaults to ${t}
${Z$} default or life-coach
${W$}=agent-recommended
Same as --recommended for agent self-hosts
${W$}=1 Same as --recommended
${U$} recommended (explicit alias for --recommended)
${j$}=1 Allow header-only auth for local development
${U$}=1 Same as --recommended
${Q$} recommended (explicit alias for --recommended)
${Y$}=1 Allow header-only auth for local development
Requests authenticate with Authorization: Bearer <token> (or ${Z$}: Bearer <token> behind proxies)
and still pass caller scope through x-goodmemory-* headers or the JSON caller field.`)}function K($,X,Z){let U=$[X+1];if(!U||U.startsWith("--"))throw Error(`Missing value for ${Z}.`);return U}function i($){if(!$)return e;let X=Number($);if(!Number.isInteger(X)||X<0||X>65535)throw Error("Expected --port to be an integer between 0 and 65535.");return X}function l($){if($===void 0||$==="default"||$==="life-coach")return $??"default";throw Error("Expected --profile to be default or life-coach.")}function r($){let X=$?.trim();if(X===void 0||X==="")return;if(X==="recommended")return X;throw Error("Expected --retrieval-preset to be recommended.")}function o($){return $==="1"||$==="true"||$==="yes"}function v$($){return $?.trim()==="agent-recommended"}function p$($,X){let Z={allowInsecure:o(X[j$]),help:!1,host:X[$$]??t,port:i(X[X$]),profile:l(X[Q$]),retrievalPreset:v$(X[Y$])||o(X[W$])?"recommended":r(X[U$]),token:X[N]?.trim()||X[A]?.trim()||void 0};for(let U=0;U<$.length;U+=1){let Q=$[U];if(Q==="--help"||Q==="-h"){Z.help=!0;continue}if(Q==="--allow-insecure"){Z.allowInsecure=!0;continue}if(Q==="--host"){Z.host=K($,U,Q),U+=1;continue}if(Q==="--port"){Z.port=i(K($,U,Q)),U+=1;continue}if(Q==="--profile"){Z.profile=l(K($,U,Q)),U+=1;continue}if(Q==="--recommended"){Z.retrievalPreset="recommended";continue}if(Q==="--retrieval-preset"){Z.retrievalPreset=r(K($,U,Q)),U+=1;continue}if(Q==="--token"){Z.token=K($,U,Q),U+=1;continue}throw Error(`Unknown option: ${Q}`)}return Z}function H$($){let X=$?.split(",").map((Z)=>Z.trim()).filter(Boolean);return X?.includes("*")?"*":X??[]}function s$($){if($==="*")return"*";if(typeof $==="string")return H$($);if(Array.isArray($))return $.filter((X)=>typeof X==="string").map((X)=>X.trim()).filter(Boolean);return[]}function u$($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function T($){return typeof $==="string"&&$.trim().length>0?$.trim():void 0}function n($){let X=$.headers.get("x-goodmemory-user-id")?.trim();if(!X)return null;return{authorizedOperations:H$($.headers.get("x-goodmemory-operations")),tenantId:$.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:X,workspaceId:$.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function i$($){if(!$||!u$($.caller))return null;let X=T($.caller.userId);if(!X)return null;return{authorizedOperations:s$($.caller.authorizedOperations),tenantId:T($.caller.tenantId),userId:X,workspaceId:T($.caller.workspaceId)}}function a($,X){let Z=T($);return Z===X||Z===`Bearer ${X}`}function l$($,X,Z){if($.headers.get("authorization")?.trim()===`Bearer ${X}`)return!0;return a($.headers.get(Z$),X)||a(Z?.bridgeAuth,X)}function r$($){return(X,Z)=>{if($.token){if(!l$(X,$.token,Z))return null;return n(X)??i$(Z)}if($.allowInsecure)return n(X);return null}}function o$($){let X=$.retrievalPreset?{retrieval:{preset:$.retrievalPreset}}:{};if($.profile==="life-coach")return{remember:u(),...X};return{...X}}function n$($){if(!$)return{embeddingEnabled:"false",retrievalTier:"unknown"};return{embeddingEnabled:String($.embeddingEnabled),retrievalTier:$.retrievalPreset?"preset-recommended":"rules-only"}}function a$($){if(!$.token&&!$.allowInsecure)throw Error(`Refusing to start without ${A} or ${N}; set a token or pass --allow-insecure for local development.`);let X=P(o$($)),Z=s({healthMetadata:{authMode:$.token?"bearer":$.allowInsecure?"insecure":"disabled",bridgeFeatures:"auth-env-alias,body-auth,body-caller",profile:$.profile,...n$(O(X))},memory:X,resolveCaller:r$($)}),U=Bun.serve({fetch:Z.fetch,hostname:$.host,port:$.port}),Q={auth:$.token?"bearer":"insecure-header",contractVersion:D,event:"ready",profile:$.profile,url:U.url.href.replace(/\/$/,"")};console.log(JSON.stringify(Q));for(let Y of["SIGINT","SIGTERM"])process.on(Y,()=>{U.stop(!0),process.exit(0)})}function t$(){let $=p$(process.argv.slice(2),process.env);if($.help){d$();return}a$($)}if(process.argv[1]!==void 0&&c$(import.meta.url)===y$(process.argv[1]))t$();export{p$ as parseArgs,n$ as deriveRetrievalHealthFields,o$ as createMemoryConfig};
Requests authenticate with Authorization: Bearer <token> (or ${X$}: Bearer <token> behind proxies)
and still pass caller scope through x-goodmemory-* headers or the JSON caller field.`)}function O($,X,Z){let U=$[X+1];if(!U||U.startsWith("--"))throw Error(`Missing value for ${Z}.`);return U}function u($){if(!$)return t;let X=Number($);if(!Number.isInteger(X)||X<0||X>65535)throw Error("Expected --port to be an integer between 0 and 65535.");return X}function i($){if($===void 0||$==="default"||$==="life-coach")return $??"default";throw Error("Expected --profile to be default or life-coach.")}function l($){let X=$?.trim();if(X===void 0||X==="")return;if(X==="recommended")return X;throw Error("Expected --retrieval-preset to be recommended.")}function r($){return $==="1"||$==="true"||$==="yes"}function v$($){return $?.trim()==="agent-recommended"}function p$($,X){let Z={allowInsecure:r(X[Y$]),help:!1,host:X[e]??a,port:u(X[$$]),profile:i(X[Z$]),retrievalPreset:v$(X[W$])||r(X[U$])?"recommended":l(X[Q$]),token:X[A]?.trim()||X[C]?.trim()||void 0};for(let U=0;U<$.length;U+=1){let Q=$[U];if(Q==="--help"||Q==="-h"){Z.help=!0;continue}if(Q==="--allow-insecure"){Z.allowInsecure=!0;continue}if(Q==="--host"){Z.host=O($,U,Q),U+=1;continue}if(Q==="--port"){Z.port=u(O($,U,Q)),U+=1;continue}if(Q==="--profile"){Z.profile=i(O($,U,Q)),U+=1;continue}if(Q==="--recommended"){Z.retrievalPreset="recommended";continue}if(Q==="--retrieval-preset"){Z.retrievalPreset=l(O($,U,Q)),U+=1;continue}if(Q==="--token"){Z.token=O($,U,Q),U+=1;continue}throw Error(`Unknown option: ${Q}`)}return Z}function j$($){let X=$?.split(",").map((Z)=>Z.trim()).filter(Boolean);return X?.includes("*")?"*":X??[]}function s$($){if($==="*")return"*";if(typeof $==="string")return j$($);if(Array.isArray($))return $.filter((X)=>typeof X==="string").map((X)=>X.trim()).filter(Boolean);return[]}function u$($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function V($){return typeof $==="string"&&$.trim().length>0?$.trim():void 0}function o($){let X=$.headers.get("x-goodmemory-user-id")?.trim();if(!X)return null;return{authorizedOperations:j$($.headers.get("x-goodmemory-operations")),tenantId:$.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:X,workspaceId:$.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function i$($){if(!$||!u$($.caller))return null;let X=V($.caller.userId);if(!X)return null;return{authorizedOperations:s$($.caller.authorizedOperations),tenantId:V($.caller.tenantId),userId:X,workspaceId:V($.caller.workspaceId)}}function n($,X){let Z=V($);return Z===X||Z===`Bearer ${X}`}function l$($,X,Z){if($.headers.get("authorization")?.trim()===`Bearer ${X}`)return!0;return n($.headers.get(X$),X)||n(Z?.bridgeAuth,X)}function r$($){return(X,Z)=>{if($.token){if(!l$(X,$.token,Z))return null;return o(X)??i$(Z)}if($.allowInsecure)return o(X);return null}}function o$($){let X=$.retrievalPreset?{retrieval:{preset:$.retrievalPreset}}:{};if($.profile==="life-coach")return{remember:s(),...X};return{...X}}function n$($){if(!$)return{embeddingEnabled:"false",retrievalTier:"unknown"};return{embeddingEnabled:String($.embeddingEnabled),retrievalTier:$.retrievalPreset?"preset-recommended":"rules-only"}}function a$($){if(!$.token&&!$.allowInsecure)throw Error(`Refusing to start without ${C} or ${A}; set a token or pass --allow-insecure for local development.`);let X=T(o$($)),Z=p({healthMetadata:{authMode:$.token?"bearer":$.allowInsecure?"insecure":"disabled",bridgeFeatures:"auth-env-alias,body-auth,body-caller",profile:$.profile,...n$(w(X))},memory:X,resolveCaller:r$($)}),U=Bun.serve({fetch:Z.fetch,hostname:$.host,port:$.port}),Q={auth:$.token?"bearer":"insecure-header",contractVersion:G,event:"ready",profile:$.profile,url:U.url.href.replace(/\/$/,"")};console.log(JSON.stringify(Q));for(let Y of["SIGINT","SIGTERM"])process.on(Y,()=>{U.stop(!0),process.exit(0)})}function t$(){let $=p$(process.argv.slice(2),process.env);if($.help){d$();return}a$($)}if(process.argv[1]!==void 0&&c$(import.meta.url)===y$(process.argv[1]))t$();export{p$ as parseArgs,n$ as deriveRetrievalHealthFields,o$ as createMemoryConfig};
#!/usr/bin/env bun
import{X as j,Y as k,Z as q,_ as g}from"./chunk-00rzhh58.js";import"./chunk-6set3gaz.js";import"./chunk-4r1rsm26.js";import"./chunk-7pd5z850.js";import"./chunk-ve2dyh5j.js";import"./chunk-w0h24t3p.js";import"./chunk-xmaks7z1.js";import{resolve as u}from"node:path";import{fileURLToPath as x}from"node:url";async function z(){let b=j({argv:process.argv.slice(2),env:process.env});if(b.mode==="error")process.stderr.write(`${b.message}
import{$ as k,_ as j,aa as q,ba as g}from"./chunk-nj5qts2b.js";import"./chunk-c5jbqdf4.js";import"./chunk-0zbze8gh.js";import"./chunk-kt9x4w7c.js";import"./chunk-wy6fj8p6.js";import{resolve as u}from"node:path";import{fileURLToPath as x}from"node:url";async function z(){let b=j({argv:process.argv.slice(2),env:process.env});if(b.mode==="error")process.stderr.write(`${b.message}
`),process.exit(1);if(b.mode==="standalone"){q(b.config),await g({allowWrite:b.allowWrite,standalone:b.config});return}await g({allowWrite:b.allowWrite||await k({host:b.host}),host:b.host})}if(process.argv[1]!==void 0&&x(import.meta.url)===u(process.argv[1]))await z();
import type { FactKind, FeedbackKind, MemoryAttributeValue, MemoryCategory, MemoryScopeKind, ReferenceKind } from "./records";
import type { MemoryScope } from "./scope";
export type ProfileField = "name" | "role" | "organization" | "location" | "timezone" | "languagePreference" | "currentProject";

@@ -7,2 +8,28 @@ export type MemoryCandidateKindHint = "profile" | "preference" | "reference" | "fact" | "feedback" | "episode" | "noise";

export type MessageAnnotationRememberMode = "always" | "never" | "auto";
export type MemoryClaimPolarity = "positive" | "negative";
export type MemoryClaimModality = "asserted" | "planned" | "attempted" | "completed" | "unknown";
export interface MemoryCandidateClaimMetadata {
predicateKey: string;
objectText: string;
objectEntity?: string;
polarity?: MemoryClaimPolarity;
modality?: MemoryClaimModality;
validFrom?: string;
validUntil?: string;
confidence?: number;
}
export interface AppendClaimProjectionInput extends MemoryScope {
sourceMemoryId: string;
subject: string;
claim: MemoryCandidateClaimMetadata;
contextualDescriptor?: string;
observedAt: string;
ingestedAt: string;
evidenceIds: string[];
sourceMessageIds: string[];
extractorVersion: string;
}
export interface ClaimProjectionWritePort {
appendClaim(input: AppendClaimProjectionInput): Promise<void>;
}
export interface MemoryCandidateMetadata {

@@ -24,2 +51,4 @@ category?: MemoryCategory;

supersedesPointer?: string;
claim?: MemoryCandidateClaimMetadata;
contextualDescriptor?: string;
}

@@ -46,4 +75,5 @@ export interface MemoryCandidateAnnotationTrace {

sourceMessageIndex: number;
sourceMessageIndexes?: number[];
sourceRole: string;
metadata?: MemoryCandidateMetadata;
}

@@ -7,2 +7,5 @@ export type MemorySourceMethod = "explicit" | "inferred" | "import" | "confirmed";

locale?: string;
localeSource?: "explicit" | "detected" | "default";
languagePackId?: string;
languagePackVersion?: string;
}

@@ -9,0 +12,0 @@ export type MemoryLifecycleState = "active" | "superseded" | "inactive";

@@ -30,2 +30,3 @@ import type { MemoryScope } from "./scope";

content: string;
observedAt?: string;
}

@@ -86,2 +87,3 @@ export interface PreferenceMemory {

lastVerificationHintAt?: string;
observedAt?: string;
validFrom?: string;

@@ -173,2 +175,3 @@ validUntil?: string;

messages: SessionMessage[];
compactedMessages?: SessionMessage[];
summary: string | null;

@@ -214,2 +217,3 @@ summaryUpToIndex: number;

storageUri: string;
contentHash?: string;
originalBytes: number;

@@ -216,0 +220,0 @@ createdAt: string;

import type { MemorySource } from "../domain/provenance";
import type { MemoryScope } from "../domain/scope";
export declare const EVIDENCE_COLLECTION = "evidence";
export declare const SOURCE_MESSAGES_COLLECTION = "source_messages_v1";
export type EvidenceAttributeValue = string | number | boolean | null;

@@ -17,2 +19,3 @@ export type EvidenceKind = "conversation_excerpt" | "tool_result_excerpt" | "document_excerpt" | "verification_result" | "correction_context";

sourceMessageIds: string[];
sourceRecordIds?: string[];
attributes?: Record<string, EvidenceAttributeValue>;

@@ -23,2 +26,12 @@ linkedMemoryIds: string[];

}
export interface SourceMessageRecord extends MemoryScope {
id: string;
schemaVersion: 1;
sourceMessageId?: string;
role: string;
content: string;
observedAt?: string;
ingestedAt: string;
contentSha256: string;
}
export declare function createEvidenceRecord(input: Pick<EvidenceRecord, "excerpt" | "id" | "kind" | "source" | "userId"> & Partial<Omit<EvidenceRecord, "excerpt" | "id" | "kind" | "source" | "userId">>): EvidenceRecord;
import type { FeedbackKind, FeedbackMemory, MemoryAttributeValue } from "../domain/records";
import type { LanguageService, ResolvedLanguageContext } from "../language";
export type BehavioralPolicyActionKind = "command" | "tool_call" | "warning";

@@ -111,2 +112,3 @@ export type BehavioralKind = "preference" | "avoidance" | "guarded_policy" | "format_contract" | "first_action" | "syntax_constraint" | "transformation_rule" | "exemplar_fact";

argumentOrder?: string[];
backupMention?: string;
canonicalFirstAction?: BehavioralPolicyAction;

@@ -150,2 +152,4 @@ computedResponseRule?: BehavioralPolicyComputedResponseRule;

kind: Exclude<FeedbackKind, "validated_pattern">;
language?: LanguageService;
languageContext?: ResolvedLanguageContext | string;
rule: string;

@@ -152,0 +156,0 @@ }

import type { EpisodeMemory } from "../domain/records";
import type { LanguageService, ResolvedLanguageContext } from "../language";
import type { ExperienceRecord, SessionArchive } from "./contracts";

@@ -175,2 +176,4 @@ import type { RecallCandidateTrace, RecallHit } from "../recall/engine";

index: RawBehavioralPrototypeIndex;
language?: LanguageService;
languageContext?: ResolvedLanguageContext | string;
maxExemplars?: number;

@@ -183,3 +186,6 @@ query: string;

export declare function selectRawBehavioralExemplars(input: SelectRawBehavioralExemplarsInput): RawBehavioralCarryoverSelection[];
export declare function renderRawBehavioralCarryoverContext(selections: readonly RawBehavioralCarryoverSelection[]): string | undefined;
export declare function renderRawBehavioralCarryoverContext(selections: readonly RawBehavioralCarryoverSelection[], options?: {
language?: LanguageService;
languageContext?: ResolvedLanguageContext | string;
}): string | undefined;
export declare function summarizeRawPrototypeIndex(index: RawBehavioralPrototypeIndex): {

@@ -186,0 +192,0 @@ exemplarCount: number;

@@ -5,2 +5,3 @@ import { type ArtifactSpillRecord, type EpisodeMemory, type FactMemory, type FeedbackMemory, type PreferenceMemory, type ReferenceMemory, type SessionJournal, type UserProfile, type WorkingMemorySnapshot } from "../domain/records";

import type { ExperienceRecord, LearningProposal, PromotionRecord, SessionArchive } from "../evolution/contracts";
import type { LanguageService, ResolvedLanguageContext } from "../language";
export interface MarkdownArtifactFile {

@@ -17,2 +18,4 @@ content: string;

interface MarkdownArtifactInput {
language: LanguageService;
languageContext: ResolvedLanguageContext;
scope: MemoryScope;

@@ -19,0 +22,0 @@ durable: {

@@ -1,1 +0,1 @@

import{$ as t,ba as r}from"../chunk-jamhwrr7.js";import{Ga as c,Ha as H,Ia as A,Ja as a,Ka as d}from"../chunk-cz5v71gv.js";import{Ab as o}from"../chunk-65h9nkw1.js";import"../chunk-m205c7rp.js";async function s(n,i){let e=o(n);if(!e?.ingestHostAgentEvent)return{recorded:!1,skippedReason:"unsupported_memory"};return e.ingestHostAgentEvent({event:t(i)})}export{t as validateHostAgentEvent,H as validateHostActionIntent,d as resolveHostActionExecutionPlan,r as isHostAgentEvent,A as isHostActionIntent,s as ingestHostAgentEvent,a as createHostAdapter,c as HostAdapterWriteError};
import{$ as t,ba as r}from"../chunk-jamhwrr7.js";import{Ea as c,Fa as H,Ga as A,Ha as a,Ia as d}from"../chunk-8d816xbx.js";import{yb as o}from"../chunk-0h5pry7v.js";import"../chunk-jr0h5wkn.js";import"../chunk-eqpe4gcb.js";async function s(n,i){let e=o(n);if(!e?.ingestHostAgentEvent)return{recorded:!1,skippedReason:"unsupported_memory"};return e.ingestHostAgentEvent({event:t(i)})}export{t as validateHostAgentEvent,H as validateHostActionIntent,d as resolveHostActionExecutionPlan,r as isHostAgentEvent,A as isHostActionIntent,s as ingestHostAgentEvent,a as createHostAdapter,c as HostAdapterWriteError};
import type { ExportMemoryResult } from "../api/contracts";
import type { LanguageService } from "../language";
import type { HostActionAssessmentResult, HostActionIntent, HostPlannedAction } from "./contracts";

@@ -7,2 +8,3 @@ export declare function buildHostPlannedActionSummary(action: HostPlannedAction): string;

intent: HostActionIntent;
language: LanguageService;
}): HostActionAssessmentResult;
import type { BuildContextResult, ExportMemoryResult, FeedbackResult, ForgetResult, GoodMemory, MemoryWriteJob, RecallInput, RecallResult, RememberResult, ReviseMemoryResult } from "../api/contracts";
import type { MemoryScope } from "../domain/scope";
import { type RememberConfig } from "../remember/profiles";
import type { RememberConfig } from "../remember/profiles";
export declare const GOODMEMORY_HTTP_MEMORY_BRIDGE_CONTRACT_VERSION = "phase-39.http-memory.v1";

@@ -5,0 +5,0 @@ export type GoodMemoryHttpBridgeOperation = "recall-context" | "remember" | "feedback" | "forget" | "export" | "revise";

@@ -1,1 +0,1 @@

import{da as K,ea as y,ia as z,ma as d,ra as m}from"../chunk-183fknnn.js";import"../chunk-m205c7rp.js";import{readFileSync as p}from"node:fs";var s=new URL("../../package.json",import.meta.url),w;function v(){if(w)return w;let Q=JSON.parse(p(s,"utf8"));if(typeof Q.version!=="string"||Q.version.length===0)throw Error("Unable to read GoodMemory package version.");return w=Q.version,w}var A="https://github.com/hjqcan/GoodMemory",V="https://goodmemory.vibenest.net";function N(Q={}){let Y=Q.version??v();return{schemaVersion:"goodmemory.capability/v2",name:"goodmemory",version:Y,kind:"memory-layer",summary:"Durable user/project memory layer for chat apps, copilots, and coding agents.",description:"GoodMemory is the product memory layer between an app or installed agent host and the model runtime: write selected facts, recall the right context, inject it into the next turn, audit what happened, and delete it when it is wrong.",notA:["llm","agent-framework","vector-database","rag-system"],license:"MIT",homepage:`${A}#readme`,repository:A,documentation:{inspector:`${A}/blob/main/docs/GoodMemory-Inspector-and-Admin-API.md`,llmsTxt:`${A}/blob/main/llms.txt`,readme:`${A}#readme`,quickstart:`${A}#quickstart-codex-or-claude-code-memory`},install:{npmGlobal:`npm install -g goodmemory@${Y}`,npmPackage:`npm install goodmemory@${Y}`,bun:`bun add goodmemory@${Y}`},memoryApi:["remember","recall","buildContext","feedback","forget","exportMemory","deleteAllMemory"],onboarding:[{audience:"installed-coding-agent-host",when:"You are, or run inside, Claude Code or Codex.",method:"cli",steps:[`npm install -g goodmemory@${Y}`,"goodmemory setup","goodmemory status"],autoDetect:"goodmemory adopt",docs:`${A}#quickstart-codex-or-claude-code-memory`},{audience:"mcp-client",when:"You speak the Model Context Protocol (Cursor, Windsurf, Cline, Claude Desktop, Gemini CLI, OpenCode, or a custom MCP client).",method:"mcp",mcpServer:{command:"goodmemory-mcp",args:["--standalone","--user-id","YOUR_USER_ID"]},autoDetect:"goodmemory adopt",docs:`${A}#standalone-mcp-for-any-client`},{audience:"framework-agent-or-backend",when:"You are a framework agent (LangGraph, custom loop) or a backend that calls memory as an HTTP service.",method:"http",endpoint:V,selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",pythonClient:"pip install goodmemory-client",docs:`${A}#pythonfastapi-http-bridge`}],mcp:{command:"goodmemory-mcp",standaloneArgs:["--standalone","--user-id","YOUR_USER_ID"],primaryTools:["goodmemory_get_context","goodmemory_remember"],readOnlyToolCount:8,writeTool:"goodmemory_remember (opt-in via --allow-write)",registryName:"io.github.hjqcan/goodmemory",docs:`${A}#standalone-mcp-for-any-client`},http:{hosted:V,liveness:`${V}/healthz`,wellKnown:`${V}/.well-known/goodmemory.json`,auth:"bearer-token",selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",endpoints:{recall:"POST /memory/recall-context",remember:"POST /memory/remember",feedback:"POST /memory/feedback",export:"POST /memory/export",forget:"POST /memory/forget",revise:"POST /memory/revise"},pythonClient:"goodmemory-client (PyPI)",docs:`${A}#pythonfastapi-http-bridge`},benchmarks:{currentClaims:[{name:"LoCoMo",config:"full 10 conversations, 1540 non-adversarial questions",metric:"independent official judge protocol; strict deterministic token-F1 reported separately",result:"official 0.8708; strict 0.6299; open-domain 0.6146 (59/96)",reference:"historical no-memory 0.0045",claimDeclaration:`${A}/blob/main/benchmark-claims/locomo.json`,runtimeProfile:"recommended+provider-embedding+provider-reranking@0.6.0",measuredPackageVersion:"0.6.0"},{name:"BEAM",config:"100K, 400 questions, 1051 rubric items",metric:"independent official unified-rubric score; strict binary and paper protocol disclosed separately",result:"unified 0.7651; strict 0.620 (248/400); generalized recall 0.8276",reference:"public full-400 same-protocol reference 0.49",claimDeclaration:`${A}/blob/main/benchmark-claims/beam.json`,runtimeProfile:"goodmemory-hybrid-generalized+evidence-pack@0.6.0",measuredPackageVersion:"0.6.0"},{name:"MemoryAgentBench",config:"Conflict Resolution 73 questions; Test-Time Learning 30 questions",metric:"deterministic upstream match-mode scoring, judge-free",result:"CR 0.959; TTL 0.933",reference:"no-memory 0.000 for CR and TTL",claimDeclaration:`${A}/blob/main/benchmark-claims/memoryagentbench.json`,runtimeProfile:"recommended-evidence-pack-cr-ttl@0.6.0",measuredPackageVersion:"0.6.0"}],historicalEvidence:{url:`${A}/tree/main/benchmark-claims`,note:"LongMemEval and ImplicitMemBench remain reproducible versioned internal evidence, not current-production claims for this package version."}},capabilities:{localFirst:!0,embeddingFreeDefault:!0,durableStore:"sqlite (default), postgres (opt-in)",audit:!0,deletion:!0,localInspector:"goodmemory inspector serve (loopback-only React console and /admin/v1 API)",correctByDefaultRecall:"Recall never silently degrades: a downgraded strategy carries routing.warnings (semantic_recall_inactive) and routing.warningMessages (semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET) instead of quietly returning the lexical floor."},canonicalSources:{prose:`${A}#readme`,benchmarks:`${A}/tree/main/benchmark-claims`,note:"This runtime descriptor exposes only claims accepted for the installed package version. Versioned historical results remain in benchmark-claims/*.json."}}}var D="phase-39.http-memory.v1",i=new Set(["export","forget","revise"]);function F(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function L(Q){return typeof Q==="string"&&Q.trim().length>0}function C(Q,Y){let X=Q[Y];if(X===void 0)return;return L(X)?X.trim():void 0}function o(Q){if(!F(Q)||!L(Q.userId))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};for(let j of["tenantId","workspaceId","agentId","sessionId"])if(Q[j]!==void 0&&!L(Q[j]))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};let Y={userId:Q.userId.trim()},X=C(Q,"tenantId"),$=C(Q,"workspaceId"),Z=C(Q,"agentId"),U=C(Q,"sessionId");if(X)Y.tenantId=X;if($)Y.workspaceId=$;if(Z)Y.agentId=Z;if(U)Y.sessionId=U;return{ok:!0,value:Y}}function r(Q){if(!Array.isArray(Q)||Q.length===0)return{code:"invalid_messages",message:"Expected messages to be a non-empty array.",ok:!1};let Y=[];for(let X of Q){if(!F(X)||!L(X.role)||!L(X.content))return{code:"invalid_messages",message:"Expected every message to include role and content string fields.",ok:!1};Y.push({content:X.content,role:X.role})}return{ok:!0,value:Y}}function f(Q){return Q===null||typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"}function n(Q){return Q==="profile"||Q==="preference"||Q==="reference"||Q==="fact"||Q==="feedback"}function u(Q){return Q==="always"||Q==="never"||Q==="auto"}function h(Q){return Q==="blocker"||Q==="open_loop"||Q==="role_update"||Q==="focus_update"||Q==="project_state"||Q==="generic_project"}function S(Q){return Q==="identity"||Q==="project"||Q==="runtime"||Q==="reference"||Q==="preference"}function E(Q){return Q==="do"||Q==="dont"||Q==="prefer"||Q==="validated_pattern"}function b(Q){return Q==="name"||Q==="role"||Q==="organization"||Q==="location"||Q==="timezone"||Q==="languagePreference"||Q==="currentProject"}function g(Q){return Q==="source_of_truth"||Q==="runbook"||Q==="doc"||Q==="dashboard"||Q==="tracker"}function l(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!F(Q))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch to be an object when provided.",ok:!1};for(let X of["category","factKind","scopeKind","subject","feedbackKind","appliesTo","profileField","preferenceCategory","preferenceValue","referenceKind","referenceTitle","referencePointer","supersedesPointer"])if(Q[X]!==void 0&&!L(Q[X]))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch string fields to be non-empty strings.",ok:!1};if(Q.factKind!==void 0&&!h(Q.factKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.factKind to be a supported fact kind.",ok:!1};if(Q.scopeKind!==void 0&&!S(Q.scopeKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.scopeKind to be a supported scope kind.",ok:!1};if(Q.feedbackKind!==void 0&&!E(Q.feedbackKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.feedbackKind to be a supported feedback kind.",ok:!1};if(Q.profileField!==void 0&&!b(Q.profileField))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.profileField to be a supported profile field.",ok:!1};if(Q.referenceKind!==void 0&&!g(Q.referenceKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.referenceKind to be a supported reference kind.",ok:!1};if(Q.tags!==void 0&&(!Array.isArray(Q.tags)||!Q.tags.every(L)))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.tags to be an array of non-empty strings.",ok:!1};if(Q.attributes!==void 0){if(!F(Q.attributes))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes to be an object.",ok:!1};for(let X of Object.values(Q.attributes))if(!f(X))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes values to be string, number, boolean, or null.",ok:!1}}let Y=F(Q.attributes)?Object.fromEntries(Object.entries(Q.attributes).filter((X)=>f(X[1]))):void 0;return{ok:!0,value:{...L(Q.category)?{category:Q.category}:{},...h(Q.factKind)?{factKind:Q.factKind}:{},...S(Q.scopeKind)?{scopeKind:Q.scopeKind}:{},...L(Q.subject)?{subject:Q.subject}:{},...Array.isArray(Q.tags)?{tags:[...Q.tags]}:{},...Y!==void 0?{attributes:Y}:{},...E(Q.feedbackKind)?{feedbackKind:Q.feedbackKind}:{},...L(Q.appliesTo)?{appliesTo:Q.appliesTo}:{},...b(Q.profileField)?{profileField:Q.profileField}:{},...L(Q.preferenceCategory)?{preferenceCategory:Q.preferenceCategory}:{},...L(Q.preferenceValue)?{preferenceValue:Q.preferenceValue}:{},...g(Q.referenceKind)?{referenceKind:Q.referenceKind}:{},...L(Q.referenceTitle)?{referenceTitle:Q.referenceTitle}:{},...L(Q.referencePointer)?{referencePointer:Q.referencePointer}:{},...L(Q.supersedesPointer)?{supersedesPointer:Q.supersedesPointer}:{}}}}function t(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!Array.isArray(Q))return{code:"invalid_annotations",message:"Expected annotations to be an array when provided.",ok:!1};let Y=[];for(let X of Q){if(!F(X))return{code:"invalid_annotations",message:"Expected every annotation to be an object.",ok:!1};let $=X.messageIndex;if(typeof $!=="number"||!Number.isInteger($))return{code:"invalid_annotations",message:"Expected every annotation to include integer messageIndex.",ok:!1};if($<0)return{code:"invalid_annotations",message:"Expected annotation.messageIndex to be non-negative.",ok:!1};if(X.remember!==void 0&&!u(X.remember))return{code:"invalid_annotations",message:"Expected annotation.remember to be always, never, or auto.",ok:!1};if(X.kindHint!==void 0&&!n(X.kindHint))return{code:"invalid_annotations",message:"Expected annotation.kindHint to be profile, preference, reference, fact, or feedback.",ok:!1};if(X.confirmed!==void 0&&typeof X.confirmed!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.confirmed to be a boolean when provided.",ok:!1};if(X.verified!==void 0&&typeof X.verified!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.verified to be a boolean when provided.",ok:!1};if(X.reason!==void 0&&!L(X.reason))return{code:"invalid_annotations",message:"Expected annotation.reason to be a non-empty string when provided.",ok:!1};let Z=l(X.metadataPatch);if(!Z.ok)return Z;Y.push({messageIndex:$,...X.remember!==void 0?{remember:X.remember}:{},...X.kindHint!==void 0?{kindHint:X.kindHint}:{},...Z.value!==void 0?{metadataPatch:Z.value}:{},...X.confirmed!==void 0?{confirmed:X.confirmed}:{},...X.verified!==void 0?{verified:X.verified}:{},...L(X.reason)?{reason:X.reason}:{}})}return{ok:!0,value:Y}}function a(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="coding_agent"||Q==="general_chat")return{ok:!0,value:Q};return{code:"invalid_retrieval_profile",message:"Expected retrievalProfile to be general_chat or coding_agent.",ok:!1}}function e(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="auto"||Q==="rules-only"||Q==="hybrid")return{ok:!0,value:Q};return{code:"invalid_recall_strategy",message:"Expected strategy to be auto, rules-only, or hybrid.",ok:!1}}function QQ(Q){if(Q===void 0)return{ok:!0,value:"system_prompt_fragment"};if(Q==="json"||Q==="markdown"||Q==="system_prompt_fragment"||Q==="developer_prompt_fragment")return{ok:!0,value:Q};return{code:"invalid_context_output",message:"Expected output to be json, markdown, system_prompt_fragment, or developer_prompt_fragment.",ok:!1}}function XQ(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="auto"||Q==="rules-only"||Q==="llm-assisted")return{ok:!0,value:Q};return{code:"invalid_extraction_strategy",message:"Expected extractionStrategy to be auto, rules-only, or llm-assisted.",ok:!1}}function O(Q,Y){if(Q===void 0&&!Y)return{ok:!0,value:void 0};if(L(Q))return{ok:!0,value:Q.trim()};return{code:"invalid_idempotency_key",message:"Expected a non-empty idempotencyKey string.",ok:!1}}function YQ(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!F(Q))return{code:"invalid_evidence",message:"Expected evidence to be an object when provided.",ok:!1};if(Q.source!=="user_message"&&Q.source!=="manual_review"&&Q.source!=="system")return{code:"invalid_evidence",message:"Expected evidence.source to be user_message, manual_review, or system.",ok:!1};return{ok:!0,value:{source:Q.source,...L(Q.message)?{message:Q.message}:{},...L(Q.excerpt)?{excerpt:Q.excerpt}:{},...L(Q.sourceUri)?{sourceUri:Q.sourceUri}:{},...Array.isArray(Q.sourceMessageIds)?{sourceMessageIds:Q.sourceMessageIds.filter(L)}:{}}}}function ZQ(Q,Y){return{error:{code:Q,message:Y},ok:!1}}function G(Q,Y){return{body:Y,statusCode:Q}}function W(Q,Y,X){return G(Q,ZQ(Y,X))}async function $Q(Q){try{let Y=await Q.json();if(!F(Y))return{code:"invalid_json_body",message:"Expected a JSON object request body.",ok:!1};return{ok:!0,value:Y}}catch{return{code:"invalid_json_body",message:"Expected a valid JSON object request body.",ok:!1}}}function LQ(Q){let Y=Q.headers.get("x-goodmemory-user-id")?.trim();if(!Y)return null;let $=Q.headers.get("x-goodmemory-operations")?.split(",").map((Z)=>Z.trim()).filter(Boolean);return{authorizedOperations:$?.includes("*")?"*":$??[],tenantId:Q.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:Y,workspaceId:Q.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function UQ(Q){if(!Q.caller)return{authorized:!1,code:"caller_required",message:"The bridge requires a backend-resolved caller identity.",statusCode:401};if(Q.caller.userId!==Q.scope.userId)return{authorized:!1,code:"scope_not_authorized",message:"Caller userId must match scope.userId.",statusCode:403};if(Q.caller.tenantId&&Q.scope.tenantId!==Q.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.tenantId must be present and match the caller tenantId.",statusCode:403};if(Q.scope.tenantId&&!Q.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide tenantId to authorize tenant-scoped memory.",statusCode:403};if(Q.caller.workspaceId&&Q.scope.workspaceId!==Q.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.workspaceId must be present and match the caller workspaceId.",statusCode:403};if(Q.scope.workspaceId&&!Q.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide workspaceId to authorize workspace-scoped memory.",statusCode:403};if(Q.sensitive&&Q.caller.authorizedOperations!=="*"){if(!Q.caller.authorizedOperations.includes(Q.operation))return{authorized:!1,code:"operation_not_authorized",message:"Caller is not authorized for this scoped memory operation.",statusCode:403}}return{authorized:!0}}function jQ(Q){return{userId:Q.userId,...Q.tenantId?{tenantId:Q.tenantId}:{},...Q.workspaceId?{workspaceId:Q.workspaceId}:{},...Q.agentId?{agentId:Q.agentId}:{},...Q.sessionId?{sessionId:Q.sessionId}:{}}}function WQ(Q){if(typeof Q==="string")return Q;return JSON.stringify(Q)}function J(Q,Y){if(!Y||Y.content.trim().length===0)return;Q.push(Y)}function _Q(Q){return Boolean(Q.profile||Q.preferences.length>0||Q.references.length>0||Q.facts.length>0||Q.feedback.length>0||Q.archives.length>0||Q.episodes.length>0||Q.workingMemory||Q.journal)}function c(Q,Y=[]){let X=Q.metadata.routingDecision.strategyExplanation,$=new Set([...X.warnings??[],...Y]);if(Q.metadata.policyApplied?.includes("semantic_candidates_unavailable"))$.add(K);let Z=y({existingMessages:X.warningMessages,warnings:[...$]});return{...X.fallbackReason?{fallbackReason:X.fallbackReason}:{},llmRefinement:X.llmRefinement,requestedStrategy:X.requestedStrategy,resolvedStrategy:X.resolvedStrategy,semanticTieBreaking:X.semanticTieBreaking,...Z.length>0?{warningMessages:Z}:{},...$.size>0?{warnings:[...$]}:{}}}function AQ(Q){if(Q.requestedStrategy!=="auto"||Q.runtimeInfo?.embeddingEnabled!==!0||Q.runtimeInfo.retrievalPreset)return[];return(Q.recall.metadata.routingDecision.strategyExplanation.resolvedStrategy??Q.recall.metadata.routingDecision.strategy)==="rules-only"?[K]:[]}function FQ(Q){return{...c(Q.recall),fallbackReason:"provider_error",providerFallback:{reason:"provider_error",recoveredStrategy:"rules-only"},requestedStrategy:Q.requestedStrategy,resolvedStrategy:"rules-only",semanticTieBreaking:!1}}function BQ(Q){let Y=[];if(Q.profile){let X=[Q.profile.identity.name,Q.profile.identity.role,Q.profile.identity.organization,...Q.profile.activeContext.goals,...Q.profile.activeContext.currentProjects].filter(L);J(Y,{content:X.join("; "),memoryId:`profile:${Q.profile.userId}`,source:"goodmemory",type:"profile"})}for(let X of Q.preferences)J(Y,{category:X.category,confidence:X.confidence,content:`${X.category}: ${WQ(X.value)}`,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"preference"});for(let X of Q.references)J(Y,{category:X.referenceKind,confidence:X.confidence,content:X.description?`${X.title}: ${X.pointer} - ${X.description}`:`${X.title}: ${X.pointer}`,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"reference"});for(let X of Q.facts)J(Y,{category:X.category,confidence:X.confidence,content:X.content,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"fact"});for(let X of Q.feedback)J(Y,{category:X.kind,confidence:X.confidence,content:X.rule,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"feedback"});for(let X of Q.episodes)J(Y,{confidence:X.confidence,content:X.summary,memoryId:X.id,source:"goodmemory",tags:X.topics,type:"episode"});if(Q.workingMemory)J(Y,{content:[Q.workingMemory.currentGoal,...Q.workingMemory.openLoops,...Q.workingMemory.temporaryDecisions??[]].filter(L).join("; "),memoryId:`working-memory:${Q.workingMemory.userId}:${Q.workingMemory.sessionId}`,source:"goodmemory",type:"working_memory"});if(Q.journal)J(Y,{content:[Q.journal.currentState,Q.journal.taskSpecification,...Q.journal.workflow??[],...Q.journal.errorsAndCorrections??[],...Q.journal.learnings??[],...Q.journal.keyResults??[],...Q.journal.worklog].filter(L).join("; "),memoryId:`session-journal:${Q.journal.userId}:${Q.journal.sessionId}`,source:"goodmemory",type:"session_journal"});return Y}async function GQ(Q,Y,X){if(!L(Y.query))return W(400,"invalid_query","Expected query to be a non-empty string.");let $=a(Y.retrievalProfile);if(!$.ok)return W(400,$.code,$.message);let Z=e(Y.strategy);if(!Z.ok)return W(400,Z.code,Z.message);let U=QQ(Y.output);if(!U.ok)return W(400,U.code,U.message);let j=typeof Y.maxTokens==="number"&&Number.isFinite(Y.maxTokens)?Math.max(1,Math.floor(Y.maxTokens)):void 0,_=Z.value??"auto",B=m(Q),M=B?.retrievalPreset!==void 0?_:_==="hybrid"?"hybrid":"rules-only",R={scope:X,query:Y.query,...$.value?{retrievalProfile:$.value}:{},strategy:M},H,x=void 0;try{H=await Q.recall(R)}catch(q){if(_==="rules-only"||!d(q))throw q;H=await Q.recall({...R,strategy:"rules-only"}),x=FQ({recall:H,requestedStrategy:_})}let T=await Q.buildContext({recall:H,output:U.value,...j?{maxTokens:j}:{}}),P=BQ(H),I=T.traceId??H.metadata.traceId;return G(200,{context:{content:T.content,estimatedTokens:T.estimatedTokens,omittedSections:T.omittedSections,output:T.output},contextText:T.content,contractVersion:D,hasContext:_Q(H),itemCount:P.length,items:P,ok:!0,operation:"recall-context",routing:x??{...c(H,AQ({recall:H,requestedStrategy:_,runtimeInfo:B})),requestedStrategy:_},...I?{traceId:I}:{}})}async function HQ(Q,Y,X){let $=r(Y.messages);if(!$.ok)return W(400,$.code,$.message);let Z=t(Y.annotations);if(!Z.ok)return W(400,Z.code,Z.message);let U=XQ(Y.extractionStrategy);if(!U.ok)return W(400,U.code,U.message);let j=Y.mode===void 0?"sync":Y.mode;if(j!=="sync"&&j!=="async")return W(400,"invalid_mode","Expected mode to be sync or async.");let _=O(Y.idempotencyKey,j==="async");if(!_.ok)return W(400,_.code,_.message);let B={scope:X,messages:$.value,...Z.value?{annotations:Z.value}:{},...U.value?{extractionStrategy:U.value}:{},...L(Y.locale)?{locale:Y.locale}:{}};if(j==="async")try{let M=await Q.jobs.enqueueRemember({...B,idempotencyKey:_.value,reason:"manual_enqueue"});return G(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_jobs",key:_.value},job:M,mode:j,ok:!0,operation:"remember"})}catch(M){if(F(M)&&M.code==="idempotency_conflict")return W(409,"idempotency_conflict","GoodMemory job idempotency key already exists for a different payload.");throw M}let k=await Q.remember(B);return G(200,{contractVersion:D,idempotency:_.value?{handledBy:"consumer_provenance_only",key:_.value}:{handledBy:"none"},mode:j,ok:!0,operation:"remember",result:k})}async function JQ(Q,Y,X){if(!L(Y.signal))return W(400,"invalid_signal","Expected signal to be a non-empty string.");let $=O(Y.idempotencyKey,!0);if(!$.ok)return W(400,$.code,$.message);let Z=F(Y.source)?Y.source:{},U=await Q.feedback({scope:X,signal:Y.signal,...L(Y.locale)?{locale:Y.locale}:{}});return G(200,{contractVersion:D,idempotency:{handledBy:"consumer_provenance_only",key:$.value},ok:!0,operation:"feedback",provenance:{...L(Z.eventId)?{eventId:Z.eventId}:{},...L(Z.proposalId)?{proposalId:Z.proposalId}:{},...L(Z.reason)?{reason:Z.reason}:{},...L(Z.reviewDecision)?{reviewDecision:Z.reviewDecision}:{},...L(Z.system)?{system:Z.system}:{}},result:U})}async function DQ(Q,Y,X){if(!L(Y.memoryId))return W(400,"invalid_memory_id","Expected memoryId to be a non-empty string.");let $=await Q.forget({memoryId:Y.memoryId,scope:X});return G(200,{contractVersion:D,ok:!0,operation:"forget",result:$})}async function MQ(Q,Y,X){let $=Y.includeRuntime===!0,Z=await Q.exportMemory({includeRuntime:$,scope:X});return G(200,{contractVersion:D,exported:Z,includeRuntime:$,ok:!0,operation:"export"})}async function TQ(Q,Y,X){let $=F(Y.target)?Y.target:null;if(!$||!L($.memoryId))return W(400,"target_memory_id_required","Expected target.memoryId. Query-resolved revision targets are out of scope.");if(!F(Y.revision)||!L(Y.revision.content))return W(400,"invalid_revision","Expected revision.content to be a non-empty string.");if(!L(Y.reason))return W(400,"invalid_reason","Expected reason to be a non-empty string.");let Z=O(Y.idempotencyKey,!0);if(!Z.ok)return W(400,Z.code,Z.message);let U=Z.value;if(!U)return W(400,"invalid_idempotency_key","Expected a non-empty idempotencyKey string.");let j=YQ(Y.evidence);if(!j.ok)return W(400,j.code,j.message);let _=await Q.reviseMemory({evidence:j.value,idempotencyKey:U,reason:Y.reason,revision:{content:Y.revision.content},scope:X,target:{memoryId:$.memoryId}});return G(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_revision",key:U},ok:!0,operation:"revise",result:_})}function zQ(Q){if(Q==="/memory/recall-context")return"recall-context";if(Q==="/memory/remember")return"remember";if(Q==="/memory/feedback")return"feedback";if(Q==="/memory/forget")return"forget";if(Q==="/memory/export")return"export";if(Q==="/memory/revise")return"revise";return null}async function wQ(Q){if(Q.operation==="recall-context")return GQ(Q.memory,Q.body,Q.scope);if(Q.operation==="remember")return HQ(Q.memory,Q.body,Q.scope);if(Q.operation==="feedback")return JQ(Q.memory,Q.body,Q.scope);if(Q.operation==="forget")return DQ(Q.memory,Q.body,Q.scope);if(Q.operation==="export")return MQ(Q.memory,Q.body,Q.scope);return TQ(Q.memory,Q.body,Q.scope)}function PQ(Q){let Y=Q.resolveCaller??LQ,X=Q.authorize??UQ;async function $(Z){if(Z.method==="GET"&&new URL(Z.url).pathname==="/healthz")return G(200,{...Q.healthMetadata??{},contractVersion:D,ok:!0,status:"ok"});if(Z.method==="GET"&&new URL(Z.url).pathname==="/.well-known/goodmemory.json")return G(200,N());if(Z.method!=="POST")return W(405,"method_not_allowed","GoodMemory bridge endpoints require POST.");let U=zQ(new URL(Z.url).pathname);if(!U)return W(404,"not_found","Unknown GoodMemory bridge endpoint.");let j=await $Q(Z);if(!j.ok)return W(400,j.code,j.message);let _=o(j.value.scope);if(!_.ok)return W(400,_.code,_.message);let B=await X({body:j.value,caller:Y(Z,j.value),operation:U,request:Z,scope:_.value,sensitive:i.has(U)});if(!B.authorized)return W(B.statusCode??403,B.code??"operation_not_authorized",B.message??"Caller is not authorized for this memory operation.");try{return await wQ({body:j.value,memory:Q.memory,operation:U,scope:_.value})}catch{return W(500,"bridge_operation_failed","GoodMemory bridge operation failed.")}}return{async fetch(Z){let U=await $(Z);return new Response(JSON.stringify(U.body),{headers:{"content-type":"application/json"},status:U.statusCode})},handle:$}}function IQ(){return{preset:"default",profiles:[{assistantOutputs:{mode:"confirmed_or_verified_only"},extends:"default",id:"life-coach",rules:[z.fact(/my top priority this quarter is (.+)/i,{category:"goal",content:({match:Q})=>`Quarterly priority: ${Q[1]??""}`,id:"life-coach-quarterly-priority",tags:["life_coach","goal"]}),z.fact(/my current goal is (.+)/i,{category:"goal",content:({match:Q})=>Q[1]??"",id:"life-coach-current-goal",tags:["life_coach","goal"]}),z.fact(/my habit is (.+)/i,{category:"habit",content:({match:Q})=>Q[1]??"",id:"life-coach-habit",tags:["life_coach","habit"]}),z.preference(/please coach me with (.+)/i,{category:"coaching_style",id:"life-coach-coaching-style",tags:["life_coach","coaching_style"],value:({match:Q})=>Q[1]??""}),z.feedback(/keep doing (.+)/i,{appliesTo:"life_coach_response",content:({match:Q})=>Q[1]??"",feedbackKind:"do",id:"life-coach-intervention-feedback",tags:["life_coach","intervention_feedback"]})],when:{agentId:"life-coach"}}]}}function qQ(Q){if(Q.ok!==!0||!Array.isArray(Q.items))throw Error("Expected a successful GoodMemory recall-context response.");let Y=Q.items.filter(F).map((X)=>({content:L(X.content)?X.content:"",memoryId:L(X.memoryId)?X.memoryId:"",type:typeof X.type==="string"?X.type:"fact"})).filter((X)=>X.memoryId.length>0&&X.content.length>0);return{context:typeof Q.contextText==="string"?Q.contextText:"",memories:Y.map((X)=>({id:X.memoryId,kind:X.type,source:"goodmemory-http-bridge",text:X.content})),metadata:{hasContext:Q.hasContext===!0,itemCount:typeof Q.itemCount==="number"?Q.itemCount:Y.length,policyBoundary:"product_owned",source:"goodmemory-http-bridge",...L(Q.traceId)?{traceId:Q.traceId}:{}}}}function NQ(Q){return jQ({agentId:Q.agentId??"life-coach",sessionId:Q.sessionId,tenantId:Q.tenantId,userId:Q.userId,workspaceId:Q.workspaceId})}export{qQ as toOneLifeMemoryContextResponse,NQ as toLifeCoachScope,IQ as createLifeCoachHttpRememberConfig,PQ as createGoodMemoryHttpMemoryBridge,BQ as buildGoodMemoryHttpMemoryItems,D as GOODMEMORY_HTTP_MEMORY_BRIDGE_CONTRACT_VERSION};
import{ca as M,da as g,ia as m,na as y}from"../chunk-t3xe8nvv.js";import"../chunk-jr0h5wkn.js";import"../chunk-eqpe4gcb.js";import{readFileSync as c}from"node:fs";var p=new URL("../../package.json",import.meta.url),z;function s(){if(z)return z;let Q=JSON.parse(c(p,"utf8")),Y=Q.goodmemoryRelease;if(typeof Q.version!=="string"||Q.version.length===0||typeof Y?.installCommandsApplyAfterPublish!=="boolean"||typeof Y.npmDistTag!=="string"||Y.npmDistTag.length===0||Y.status!=="release-candidate"&&Y.status!=="stable")throw Error("Unable to read GoodMemory package release metadata.");return z={goodmemoryRelease:{installCommandsApplyAfterPublish:Y.installCommandsApplyAfterPublish,npmDistTag:Y.npmDistTag,status:Y.status},version:Q.version},z}var A="https://github.com/hjqcan/GoodMemory",w="https://goodmemory.vibenest.net";function I(Q={}){let Y=Q.packageMetadata??s(),X=Q.version??Y.version;return{schemaVersion:"goodmemory.capability/v2",name:"goodmemory",version:X,kind:"memory-layer",summary:"Durable user/project memory layer for chat apps, copilots, and coding agents.",description:"GoodMemory is the product memory layer between an app or installed agent host and the model runtime: write selected facts, recall the right context, inject it into the next turn, audit what happened, and delete it when it is wrong.",notA:["llm","agent-framework","vector-database","rag-system"],license:"MIT",homepage:`${A}#readme`,repository:A,documentation:{inspector:`${A}/blob/main/docs/GoodMemory-Inspector-and-Admin-API.md`,llmsTxt:`${A}/blob/main/llms.txt`,readme:`${A}#readme`,quickstart:`${A}#quickstart-codex-or-claude-code-memory`},install:{npmGlobal:`npm install -g goodmemory@${X}`,npmPackage:`npm install goodmemory@${X}`,bun:`bun add goodmemory@${X}`},releaseStatus:{...Y.goodmemoryRelease,tarball:`goodmemory-${X}.tgz`},memoryApi:["remember","recall","buildContext","feedback","forget","exportMemory","deleteAllMemory"],onboarding:[{audience:"installed-coding-agent-host",when:"You are, or run inside, Claude Code or Codex.",method:"cli",steps:[`npm install -g goodmemory@${X}`,"goodmemory setup","goodmemory status"],autoDetect:"goodmemory adopt",docs:`${A}#quickstart-codex-or-claude-code-memory`},{audience:"mcp-client",when:"You speak the Model Context Protocol (Cursor, Windsurf, Cline, Claude Desktop, Gemini CLI, OpenCode, or a custom MCP client).",method:"mcp",mcpServer:{command:"goodmemory-mcp",args:["--standalone","--user-id","YOUR_USER_ID"]},autoDetect:"goodmemory adopt",docs:`${A}#standalone-mcp-for-any-client`},{audience:"framework-agent-or-backend",when:"You are a framework agent (LangGraph, custom loop) or a backend that calls memory as an HTTP service.",method:"http",endpoint:w,selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",pythonClient:"pip install goodmemory-client",docs:`${A}#pythonfastapi-http-bridge`}],mcp:{command:"goodmemory-mcp",standaloneArgs:["--standalone","--user-id","YOUR_USER_ID"],primaryTools:["goodmemory_get_context","goodmemory_remember"],readOnlyToolCount:8,writeTool:"goodmemory_remember (opt-in via --allow-write)",registryName:"io.github.hjqcan/goodmemory",docs:`${A}#standalone-mcp-for-any-client`},http:{hosted:w,liveness:`${w}/healthz`,wellKnown:`${w}/.well-known/goodmemory.json`,auth:"bearer-token",selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",endpoints:{recall:"POST /memory/recall-context",remember:"POST /memory/remember",feedback:"POST /memory/feedback",export:"POST /memory/export",forget:"POST /memory/forget",revise:"POST /memory/revise"},pythonClient:"goodmemory-client (PyPI)",docs:`${A}#pythonfastapi-http-bridge`},benchmarks:{currentClaims:[],historicalEvidence:{url:`${A}/tree/main/benchmark-claims`,note:`The v0.6.0 LoCoMo, BEAM, and MemoryAgentBench results, plus older LongMemEval and ImplicitMemBench runs, remain reproducible versioned evidence. None is a current ${X} production claim until rerun against this package line. LongMemEval and ImplicitMemBench remain internal evidence.`}},capabilities:{localFirst:!0,embeddingFreeDefault:!0,builtInLanguagePacks:["en","zh-Hans","zh-Hant","ja","ko","fr","es"],durableStore:"sqlite (default), postgres (opt-in)",audit:!0,deletion:!0,localInspector:"goodmemory inspector serve (loopback-only React console and /admin/v1 API)",correctByDefaultRecall:"Recall never silently degrades: a downgraded strategy carries routing.warnings (semantic_recall_inactive) and routing.warningMessages (semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET) instead of quietly returning the lexical floor."},canonicalSources:{prose:`${A}#readme`,benchmarks:`${A}/tree/main/benchmark-claims`,note:"Benchmark entries keep explicit measuredPackageVersion provenance; a package version bump never relabels historical results. Source declarations remain in benchmark-claims/*.json."}}}var D="phase-39.http-memory.v1",v=new Set(["export","forget","revise"]);function F(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function L(Q){return typeof Q==="string"&&Q.trim().length>0}function C(Q,Y){let X=Q[Y];if(X===void 0)return;return L(X)?X.trim():void 0}function i(Q){if(!F(Q)||!L(Q.userId))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};for(let j of["tenantId","workspaceId","agentId","sessionId"])if(Q[j]!==void 0&&!L(Q[j]))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};let Y={userId:Q.userId.trim()},X=C(Q,"tenantId"),$=C(Q,"workspaceId"),Z=C(Q,"agentId"),U=C(Q,"sessionId");if(X)Y.tenantId=X;if($)Y.workspaceId=$;if(Z)Y.agentId=Z;if(U)Y.sessionId=U;return{ok:!0,value:Y}}function o(Q){if(!Array.isArray(Q)||Q.length===0)return{code:"invalid_messages",message:"Expected messages to be a non-empty array.",ok:!1};let Y=[];for(let X of Q){if(!F(X)||!L(X.role)||!L(X.content))return{code:"invalid_messages",message:"Expected every message to include role and content string fields.",ok:!1};Y.push({content:X.content,role:X.role})}return{ok:!0,value:Y}}function q(Q){return Q===null||typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"}function r(Q){return Q==="profile"||Q==="preference"||Q==="reference"||Q==="fact"||Q==="feedback"}function n(Q){return Q==="always"||Q==="never"||Q==="auto"}function N(Q){return Q==="blocker"||Q==="open_loop"||Q==="role_update"||Q==="focus_update"||Q==="project_state"||Q==="generic_project"}function f(Q){return Q==="identity"||Q==="project"||Q==="runtime"||Q==="reference"||Q==="preference"}function E(Q){return Q==="do"||Q==="dont"||Q==="prefer"||Q==="validated_pattern"}function S(Q){return Q==="name"||Q==="role"||Q==="organization"||Q==="location"||Q==="timezone"||Q==="languagePreference"||Q==="currentProject"}function b(Q){return Q==="source_of_truth"||Q==="runbook"||Q==="doc"||Q==="dashboard"||Q==="tracker"}function u(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!F(Q))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch to be an object when provided.",ok:!1};for(let X of["category","factKind","scopeKind","subject","feedbackKind","appliesTo","profileField","preferenceCategory","preferenceValue","referenceKind","referenceTitle","referencePointer","supersedesPointer"])if(Q[X]!==void 0&&!L(Q[X]))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch string fields to be non-empty strings.",ok:!1};if(Q.factKind!==void 0&&!N(Q.factKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.factKind to be a supported fact kind.",ok:!1};if(Q.scopeKind!==void 0&&!f(Q.scopeKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.scopeKind to be a supported scope kind.",ok:!1};if(Q.feedbackKind!==void 0&&!E(Q.feedbackKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.feedbackKind to be a supported feedback kind.",ok:!1};if(Q.profileField!==void 0&&!S(Q.profileField))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.profileField to be a supported profile field.",ok:!1};if(Q.referenceKind!==void 0&&!b(Q.referenceKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.referenceKind to be a supported reference kind.",ok:!1};if(Q.tags!==void 0&&(!Array.isArray(Q.tags)||!Q.tags.every(L)))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.tags to be an array of non-empty strings.",ok:!1};if(Q.attributes!==void 0){if(!F(Q.attributes))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes to be an object.",ok:!1};for(let X of Object.values(Q.attributes))if(!q(X))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes values to be string, number, boolean, or null.",ok:!1}}let Y=F(Q.attributes)?Object.fromEntries(Object.entries(Q.attributes).filter((X)=>q(X[1]))):void 0;return{ok:!0,value:{...L(Q.category)?{category:Q.category}:{},...N(Q.factKind)?{factKind:Q.factKind}:{},...f(Q.scopeKind)?{scopeKind:Q.scopeKind}:{},...L(Q.subject)?{subject:Q.subject}:{},...Array.isArray(Q.tags)?{tags:[...Q.tags]}:{},...Y!==void 0?{attributes:Y}:{},...E(Q.feedbackKind)?{feedbackKind:Q.feedbackKind}:{},...L(Q.appliesTo)?{appliesTo:Q.appliesTo}:{},...S(Q.profileField)?{profileField:Q.profileField}:{},...L(Q.preferenceCategory)?{preferenceCategory:Q.preferenceCategory}:{},...L(Q.preferenceValue)?{preferenceValue:Q.preferenceValue}:{},...b(Q.referenceKind)?{referenceKind:Q.referenceKind}:{},...L(Q.referenceTitle)?{referenceTitle:Q.referenceTitle}:{},...L(Q.referencePointer)?{referencePointer:Q.referencePointer}:{},...L(Q.supersedesPointer)?{supersedesPointer:Q.supersedesPointer}:{}}}}function l(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!Array.isArray(Q))return{code:"invalid_annotations",message:"Expected annotations to be an array when provided.",ok:!1};let Y=[];for(let X of Q){if(!F(X))return{code:"invalid_annotations",message:"Expected every annotation to be an object.",ok:!1};let $=X.messageIndex;if(typeof $!=="number"||!Number.isInteger($))return{code:"invalid_annotations",message:"Expected every annotation to include integer messageIndex.",ok:!1};if($<0)return{code:"invalid_annotations",message:"Expected annotation.messageIndex to be non-negative.",ok:!1};if(X.remember!==void 0&&!n(X.remember))return{code:"invalid_annotations",message:"Expected annotation.remember to be always, never, or auto.",ok:!1};if(X.kindHint!==void 0&&!r(X.kindHint))return{code:"invalid_annotations",message:"Expected annotation.kindHint to be profile, preference, reference, fact, or feedback.",ok:!1};if(X.confirmed!==void 0&&typeof X.confirmed!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.confirmed to be a boolean when provided.",ok:!1};if(X.verified!==void 0&&typeof X.verified!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.verified to be a boolean when provided.",ok:!1};if(X.reason!==void 0&&!L(X.reason))return{code:"invalid_annotations",message:"Expected annotation.reason to be a non-empty string when provided.",ok:!1};let Z=u(X.metadataPatch);if(!Z.ok)return Z;Y.push({messageIndex:$,...X.remember!==void 0?{remember:X.remember}:{},...X.kindHint!==void 0?{kindHint:X.kindHint}:{},...Z.value!==void 0?{metadataPatch:Z.value}:{},...X.confirmed!==void 0?{confirmed:X.confirmed}:{},...X.verified!==void 0?{verified:X.verified}:{},...L(X.reason)?{reason:X.reason}:{}})}return{ok:!0,value:Y}}function t(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="coding_agent"||Q==="general_chat")return{ok:!0,value:Q};return{code:"invalid_retrieval_profile",message:"Expected retrievalProfile to be general_chat or coding_agent.",ok:!1}}function a(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="auto"||Q==="rules-only"||Q==="hybrid")return{ok:!0,value:Q};return{code:"invalid_recall_strategy",message:"Expected strategy to be auto, rules-only, or hybrid.",ok:!1}}function e(Q){if(Q===void 0)return{ok:!0,value:"system_prompt_fragment"};if(Q==="json"||Q==="markdown"||Q==="system_prompt_fragment"||Q==="developer_prompt_fragment")return{ok:!0,value:Q};return{code:"invalid_context_output",message:"Expected output to be json, markdown, system_prompt_fragment, or developer_prompt_fragment.",ok:!1}}function QQ(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="auto"||Q==="rules-only"||Q==="llm-assisted")return{ok:!0,value:Q};return{code:"invalid_extraction_strategy",message:"Expected extractionStrategy to be auto, rules-only, or llm-assisted.",ok:!1}}function O(Q,Y){if(Q===void 0&&!Y)return{ok:!0,value:void 0};if(L(Q))return{ok:!0,value:Q.trim()};return{code:"invalid_idempotency_key",message:"Expected a non-empty idempotencyKey string.",ok:!1}}function XQ(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!F(Q))return{code:"invalid_evidence",message:"Expected evidence to be an object when provided.",ok:!1};if(Q.source!=="user_message"&&Q.source!=="manual_review"&&Q.source!=="system")return{code:"invalid_evidence",message:"Expected evidence.source to be user_message, manual_review, or system.",ok:!1};return{ok:!0,value:{source:Q.source,...L(Q.message)?{message:Q.message}:{},...L(Q.excerpt)?{excerpt:Q.excerpt}:{},...L(Q.sourceUri)?{sourceUri:Q.sourceUri}:{},...Array.isArray(Q.sourceMessageIds)?{sourceMessageIds:Q.sourceMessageIds.filter(L)}:{}}}}function YQ(Q,Y){return{error:{code:Q,message:Y},ok:!1}}function G(Q,Y){return{body:Y,statusCode:Q}}function W(Q,Y,X){return G(Q,YQ(Y,X))}async function ZQ(Q){try{let Y=await Q.json();if(!F(Y))return{code:"invalid_json_body",message:"Expected a JSON object request body.",ok:!1};return{ok:!0,value:Y}}catch{return{code:"invalid_json_body",message:"Expected a valid JSON object request body.",ok:!1}}}function $Q(Q){let Y=Q.headers.get("x-goodmemory-user-id")?.trim();if(!Y)return null;let $=Q.headers.get("x-goodmemory-operations")?.split(",").map((Z)=>Z.trim()).filter(Boolean);return{authorizedOperations:$?.includes("*")?"*":$??[],tenantId:Q.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:Y,workspaceId:Q.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function LQ(Q){if(!Q.caller)return{authorized:!1,code:"caller_required",message:"The bridge requires a backend-resolved caller identity.",statusCode:401};if(Q.caller.userId!==Q.scope.userId)return{authorized:!1,code:"scope_not_authorized",message:"Caller userId must match scope.userId.",statusCode:403};if(Q.caller.tenantId&&Q.scope.tenantId!==Q.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.tenantId must be present and match the caller tenantId.",statusCode:403};if(Q.scope.tenantId&&!Q.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide tenantId to authorize tenant-scoped memory.",statusCode:403};if(Q.caller.workspaceId&&Q.scope.workspaceId!==Q.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.workspaceId must be present and match the caller workspaceId.",statusCode:403};if(Q.scope.workspaceId&&!Q.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide workspaceId to authorize workspace-scoped memory.",statusCode:403};if(Q.sensitive&&Q.caller.authorizedOperations!=="*"){if(!Q.caller.authorizedOperations.includes(Q.operation))return{authorized:!1,code:"operation_not_authorized",message:"Caller is not authorized for this scoped memory operation.",statusCode:403}}return{authorized:!0}}function UQ(Q){return{userId:Q.userId,...Q.tenantId?{tenantId:Q.tenantId}:{},...Q.workspaceId?{workspaceId:Q.workspaceId}:{},...Q.agentId?{agentId:Q.agentId}:{},...Q.sessionId?{sessionId:Q.sessionId}:{}}}function jQ(Q){if(typeof Q==="string")return Q;return JSON.stringify(Q)}function H(Q,Y){if(!Y||Y.content.trim().length===0)return;Q.push(Y)}function WQ(Q){return Boolean(Q.profile||Q.preferences.length>0||Q.references.length>0||Q.facts.length>0||Q.feedback.length>0||Q.archives.length>0||Q.episodes.length>0||Q.workingMemory||Q.journal)}function d(Q,Y=[]){let X=Q.metadata.routingDecision.strategyExplanation,$=new Set([...X.warnings??[],...Y]);if(Q.metadata.policyApplied?.includes("semantic_candidates_unavailable"))$.add(M);let Z=g({existingMessages:X.warningMessages,warnings:[...$]});return{...X.fallbackReason?{fallbackReason:X.fallbackReason}:{},llmRefinement:X.llmRefinement,requestedStrategy:X.requestedStrategy,resolvedStrategy:X.resolvedStrategy,semanticTieBreaking:X.semanticTieBreaking,...Z.length>0?{warningMessages:Z}:{},...$.size>0?{warnings:[...$]}:{}}}function _Q(Q){if(Q.requestedStrategy!=="auto"||Q.runtimeInfo?.embeddingEnabled!==!0||Q.runtimeInfo.retrievalPreset)return[];return(Q.recall.metadata.routingDecision.strategyExplanation.resolvedStrategy??Q.recall.metadata.routingDecision.strategy)==="rules-only"?[M]:[]}function AQ(Q){return{...d(Q.recall),fallbackReason:"provider_error",providerFallback:{reason:"provider_error",recoveredStrategy:"rules-only"},requestedStrategy:Q.requestedStrategy,resolvedStrategy:"rules-only",semanticTieBreaking:!1}}function FQ(Q){let Y=[];if(Q.profile){let X=[Q.profile.identity.name,Q.profile.identity.role,Q.profile.identity.organization,...Q.profile.activeContext.goals,...Q.profile.activeContext.currentProjects].filter(L);H(Y,{content:X.join("; "),memoryId:`profile:${Q.profile.userId}`,source:"goodmemory",type:"profile"})}for(let X of Q.preferences)H(Y,{category:X.category,confidence:X.confidence,content:`${X.category}: ${jQ(X.value)}`,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"preference"});for(let X of Q.references)H(Y,{category:X.referenceKind,confidence:X.confidence,content:X.description?`${X.title}: ${X.pointer} - ${X.description}`:`${X.title}: ${X.pointer}`,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"reference"});for(let X of Q.facts)H(Y,{category:X.category,confidence:X.confidence,content:X.content,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"fact"});for(let X of Q.feedback)H(Y,{category:X.kind,confidence:X.confidence,content:X.rule,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"feedback"});for(let X of Q.episodes)H(Y,{confidence:X.confidence,content:X.summary,memoryId:X.id,source:"goodmemory",tags:X.topics,type:"episode"});if(Q.workingMemory)H(Y,{content:[Q.workingMemory.currentGoal,...Q.workingMemory.openLoops,...Q.workingMemory.temporaryDecisions??[]].filter(L).join("; "),memoryId:`working-memory:${Q.workingMemory.userId}:${Q.workingMemory.sessionId}`,source:"goodmemory",type:"working_memory"});if(Q.journal)H(Y,{content:[Q.journal.currentState,Q.journal.taskSpecification,...Q.journal.workflow??[],...Q.journal.errorsAndCorrections??[],...Q.journal.learnings??[],...Q.journal.keyResults??[],...Q.journal.worklog].filter(L).join("; "),memoryId:`session-journal:${Q.journal.userId}:${Q.journal.sessionId}`,source:"goodmemory",type:"session_journal"});return Y}async function BQ(Q,Y,X){if(!L(Y.query))return W(400,"invalid_query","Expected query to be a non-empty string.");let $=t(Y.retrievalProfile);if(!$.ok)return W(400,$.code,$.message);let Z=a(Y.strategy);if(!Z.ok)return W(400,Z.code,Z.message);let U=e(Y.output);if(!U.ok)return W(400,U.code,U.message);let j=typeof Y.maxTokens==="number"&&Number.isFinite(Y.maxTokens)?Math.max(1,Math.floor(Y.maxTokens)):void 0,_=Z.value??"auto",B=y(Q),J=B?.retrievalPreset!==void 0?_:_==="hybrid"?"hybrid":"rules-only",R={scope:X,query:Y.query,...$.value?{retrievalProfile:$.value}:{},strategy:J},V,P=void 0;try{V=await Q.recall(R)}catch(h){if(_==="rules-only"||!m(h))throw h;V=await Q.recall({...R,strategy:"rules-only"}),P=AQ({recall:V,requestedStrategy:_})}let T=await Q.buildContext({recall:V,output:U.value,...j?{maxTokens:j}:{}}),k=FQ(V),x=T.traceId??V.metadata.traceId;return G(200,{context:{content:T.content,estimatedTokens:T.estimatedTokens,omittedSections:T.omittedSections,output:T.output},contextText:T.content,contractVersion:D,hasContext:WQ(V),itemCount:k.length,items:k,ok:!0,operation:"recall-context",routing:P??{...d(V,_Q({recall:V,requestedStrategy:_,runtimeInfo:B})),requestedStrategy:_},...x?{traceId:x}:{}})}async function GQ(Q,Y,X){let $=o(Y.messages);if(!$.ok)return W(400,$.code,$.message);let Z=l(Y.annotations);if(!Z.ok)return W(400,Z.code,Z.message);let U=QQ(Y.extractionStrategy);if(!U.ok)return W(400,U.code,U.message);let j=Y.mode===void 0?"sync":Y.mode;if(j!=="sync"&&j!=="async")return W(400,"invalid_mode","Expected mode to be sync or async.");let _=O(Y.idempotencyKey,j==="async");if(!_.ok)return W(400,_.code,_.message);let B={scope:X,messages:$.value,...Z.value?{annotations:Z.value}:{},...U.value?{extractionStrategy:U.value}:{},...L(Y.locale)?{locale:Y.locale}:{}};if(j==="async")try{let J=await Q.jobs.enqueueRemember({...B,idempotencyKey:_.value,reason:"manual_enqueue"});return G(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_jobs",key:_.value},job:J,mode:j,ok:!0,operation:"remember"})}catch(J){if(F(J)&&J.code==="idempotency_conflict")return W(409,"idempotency_conflict","GoodMemory job idempotency key already exists for a different payload.");throw J}let K=await Q.remember(B);return G(200,{contractVersion:D,idempotency:_.value?{handledBy:"consumer_provenance_only",key:_.value}:{handledBy:"none"},mode:j,ok:!0,operation:"remember",result:K})}async function VQ(Q,Y,X){if(!L(Y.signal))return W(400,"invalid_signal","Expected signal to be a non-empty string.");let $=O(Y.idempotencyKey,!0);if(!$.ok)return W(400,$.code,$.message);let Z=F(Y.source)?Y.source:{},U=await Q.feedback({scope:X,signal:Y.signal,...L(Y.locale)?{locale:Y.locale}:{}});return G(200,{contractVersion:D,idempotency:{handledBy:"consumer_provenance_only",key:$.value},ok:!0,operation:"feedback",provenance:{...L(Z.eventId)?{eventId:Z.eventId}:{},...L(Z.proposalId)?{proposalId:Z.proposalId}:{},...L(Z.reason)?{reason:Z.reason}:{},...L(Z.reviewDecision)?{reviewDecision:Z.reviewDecision}:{},...L(Z.system)?{system:Z.system}:{}},result:U})}async function HQ(Q,Y,X){if(!L(Y.memoryId))return W(400,"invalid_memory_id","Expected memoryId to be a non-empty string.");let $=await Q.forget({memoryId:Y.memoryId,scope:X});return G(200,{contractVersion:D,ok:!0,operation:"forget",result:$})}async function DQ(Q,Y,X){let $=Y.includeRuntime===!0,Z=await Q.exportMemory({includeRuntime:$,scope:X});return G(200,{contractVersion:D,exported:Z,includeRuntime:$,ok:!0,operation:"export"})}async function JQ(Q,Y,X){let $=F(Y.target)?Y.target:null;if(!$||!L($.memoryId))return W(400,"target_memory_id_required","Expected target.memoryId. Query-resolved revision targets are out of scope.");if(!F(Y.revision)||!L(Y.revision.content))return W(400,"invalid_revision","Expected revision.content to be a non-empty string.");if(!L(Y.reason))return W(400,"invalid_reason","Expected reason to be a non-empty string.");let Z=O(Y.idempotencyKey,!0);if(!Z.ok)return W(400,Z.code,Z.message);let U=Z.value;if(!U)return W(400,"invalid_idempotency_key","Expected a non-empty idempotencyKey string.");let j=XQ(Y.evidence);if(!j.ok)return W(400,j.code,j.message);let _=await Q.reviseMemory({evidence:j.value,idempotencyKey:U,reason:Y.reason,revision:{content:Y.revision.content},scope:X,target:{memoryId:$.memoryId}});return G(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_revision",key:U},ok:!0,operation:"revise",result:_})}function TQ(Q){if(Q==="/memory/recall-context")return"recall-context";if(Q==="/memory/remember")return"remember";if(Q==="/memory/feedback")return"feedback";if(Q==="/memory/forget")return"forget";if(Q==="/memory/export")return"export";if(Q==="/memory/revise")return"revise";return null}async function zQ(Q){if(Q.operation==="recall-context")return BQ(Q.memory,Q.body,Q.scope);if(Q.operation==="remember")return GQ(Q.memory,Q.body,Q.scope);if(Q.operation==="feedback")return VQ(Q.memory,Q.body,Q.scope);if(Q.operation==="forget")return HQ(Q.memory,Q.body,Q.scope);if(Q.operation==="export")return DQ(Q.memory,Q.body,Q.scope);return JQ(Q.memory,Q.body,Q.scope)}function PQ(Q){let Y=Q.resolveCaller??$Q,X=Q.authorize??LQ;async function $(Z){if(Z.method==="GET"&&new URL(Z.url).pathname==="/healthz")return G(200,{...Q.healthMetadata??{},contractVersion:D,ok:!0,status:"ok"});if(Z.method==="GET"&&new URL(Z.url).pathname==="/.well-known/goodmemory.json")return G(200,I());if(Z.method!=="POST")return W(405,"method_not_allowed","GoodMemory bridge endpoints require POST.");let U=TQ(new URL(Z.url).pathname);if(!U)return W(404,"not_found","Unknown GoodMemory bridge endpoint.");let j=await ZQ(Z);if(!j.ok)return W(400,j.code,j.message);let _=i(j.value.scope);if(!_.ok)return W(400,_.code,_.message);let B=await X({body:j.value,caller:Y(Z,j.value),operation:U,request:Z,scope:_.value,sensitive:v.has(U)});if(!B.authorized)return W(B.statusCode??403,B.code??"operation_not_authorized",B.message??"Caller is not authorized for this memory operation.");try{return await zQ({body:j.value,memory:Q.memory,operation:U,scope:_.value})}catch{return W(500,"bridge_operation_failed","GoodMemory bridge operation failed.")}}return{async fetch(Z){let U=await $(Z);return new Response(JSON.stringify(U.body),{headers:{"content-type":"application/json"},status:U.statusCode})},handle:$}}function kQ(){return{preset:"default",profiles:[{assistantOutputs:{mode:"confirmed_or_verified_only"},extends:"default",id:"life-coach",when:{agentId:"life-coach"}}]}}function xQ(Q){if(Q.ok!==!0||!Array.isArray(Q.items))throw Error("Expected a successful GoodMemory recall-context response.");let Y=Q.items.filter(F).map((X)=>({content:L(X.content)?X.content:"",memoryId:L(X.memoryId)?X.memoryId:"",type:typeof X.type==="string"?X.type:"fact"})).filter((X)=>X.memoryId.length>0&&X.content.length>0);return{context:typeof Q.contextText==="string"?Q.contextText:"",memories:Y.map((X)=>({id:X.memoryId,kind:X.type,source:"goodmemory-http-bridge",text:X.content})),metadata:{hasContext:Q.hasContext===!0,itemCount:typeof Q.itemCount==="number"?Q.itemCount:Y.length,policyBoundary:"product_owned",source:"goodmemory-http-bridge",...L(Q.traceId)?{traceId:Q.traceId}:{}}}}function hQ(Q){return UQ({agentId:Q.agentId??"life-coach",sessionId:Q.sessionId,tenantId:Q.tenantId,userId:Q.userId,workspaceId:Q.workspaceId})}export{xQ as toOneLifeMemoryContextResponse,hQ as toLifeCoachScope,kQ as createLifeCoachHttpRememberConfig,PQ as createGoodMemoryHttpMemoryBridge,FQ as buildGoodMemoryHttpMemoryItems,D as GOODMEMORY_HTTP_MEMORY_BRIDGE_CONTRACT_VERSION};

@@ -7,4 +7,4 @@ export type { MemoryScope } from "./domain/scope";

export { createEpisodeMemory, createFactMemory, createFeedbackMemory, createPreferenceMemory, createReferenceMemory, createSessionBuffer, createSessionJournal, createUserProfile, createWorkingMemorySnapshot, isFactExpired, } from "./domain/records";
export type { EvidenceKind, EvidenceRecord, } from "./evidence/contracts";
export { createEvidenceRecord, EVIDENCE_COLLECTION, } from "./evidence/contracts";
export type { EvidenceKind, EvidenceRecord, SourceMessageRecord, } from "./evidence/contracts";
export { createEvidenceRecord, EVIDENCE_COLLECTION, SOURCE_MESSAGES_COLLECTION, } from "./evidence/contracts";
export type { EmbeddingAdapter } from "./embedding/contracts";

@@ -19,2 +19,5 @@ export { createLocalEmbeddingAdapter, embedTextLocally, } from "./embedding/localEmbeddingAdapter";

export type { RecallFusionCandidateTrace, RecallFusionRunTrace, RecallRerankerScoreTrace, RecallRerankerTrace, RecallRetrievalChannel, RecallRetrievalChannelTrace, RecallRetrievalSourceCollection, RecallRetrievalTrace, } from "./recall/retrievalTrace";
export type { EvidenceLedgerEntry, } from "./recall/evidenceLedger";
export type { ClaimProjection, ClaimProjectionState, ClaimProjectionStatus, } from "./recall/projections/contracts";
export type { RecallAggregation, RecallEvidenceNeed, RecallPlan, RecallPlanAssistant, RecallPlanAssistantInput, RecallPlanResolution, RecallPlanUncertainty, TemporalConstraint, } from "./recall/recallPlan";
export { resolveCurrentValue, resolveCurrentValuesByGroup, } from "./answer/currentValueResolution";

@@ -26,8 +29,8 @@ export type { CurrentValueEntry, CurrentValueReason, CurrentValueResolution, } from "./answer/currentValueResolution";

export { createMemorySource, transitionLifecycle, } from "./domain/provenance";
export type { ConditionalDocumentWriteBatch, DocumentStore, DocumentWriteOperation, SessionStore, StorageDocument, StorageFilter, VectorRecord, VectorSearchInput, VectorSearchResult, VectorStore, } from "./storage/contracts";
export { matchesFilter, shallowMergeDocument, } from "./storage/contracts";
export type { ConditionalDocumentWriteBatch, DocumentStore, DocumentWriteOperation, ProjectionCapableDocumentStore, SessionStore, StorageDocument, StorageFilter, VectorRecord, VectorSearchInput, VectorSearchResult, VectorStore, } from "./storage/contracts";
export { PROJECTION_BATCH_SEMANTICS, isProjectionCapableDocumentStore, matchesFilter, shallowMergeDocument, } from "./storage/contracts";
export { createInMemoryDocumentStore, createInMemorySessionStore, createInMemoryVectorStore, } from "./storage/memory";
export { createSQLiteDocumentStore, createSQLiteSessionStore, createSQLiteVectorStore, } from "./storage/sqlitePublic";
export type { PostgresStorageConfig } from "./storage/postgresPublic";
export { createPostgresDocumentStore, createPostgresSessionStore, createPostgresVectorStore, } from "./storage/postgresPublic";
export type { PostgresStorageConfig, PostgresStorageMigrationEvent, PostgresStorageMigrationOptions, } from "./storage/postgresPublic";
export { createPostgresDocumentStore, createPostgresSessionStore, createPostgresVectorStore, migratePostgresStorageBackend, } from "./storage/postgresPublic";
export type { MemoryPacket } from "./recall/contextBuilder";

@@ -44,3 +47,4 @@ export { buildMemoryPacket, renderMemoryPacket, } from "./recall/contextBuilder";

export { rememberRules } from "./remember/profiles";
export type { LanguageAdapter, LanguageConfig, LocaleDetector, LocaleDetectorInput, LocaleResolutionSource, ResolvedLanguageContext, } from "./language";
export type { LanguageCandidateExtractionInput, LanguageAnalyzerManifest, LanguageAnalyzerManifestPack, LanguageBehavioralRuleAnalysis, LanguageConfig, LanguageContentAnalysis, LanguageDetectionInput, LanguageDetectionMode, LanguageDetectionStrength, LanguageEntityCandidateInput, LanguageEntityMention, LanguagePack, LanguageQueryAnalysis, LanguageRenderInput, LanguageRenderKey, LanguageService, LanguageSourceOfTruthDirective, LanguageTemporalExpression, LocaleDetector, LocaleDetectorInput, LocaleResolutionSource, ResolvedLanguageContext, } from "./language";
export { createChineseLanguagePack, createEnglishLanguagePack, createFrenchLanguagePack, createJapaneseLanguagePack, createKoreanLanguagePack, createLanguageService, createNeutralLanguagePack, createSpanishLanguagePack, } from "./language";
export type { ClassifiedCandidate, RememberEvent as RememberPipelineEvent, RememberResult as RememberPipelineResult, } from "./remember/engine";

@@ -51,2 +55,3 @@ export type { ConflictResolution, GoodMemoryPolicyHooks, PolicyContext, PolicyMemoryRecord, } from "./policy/hooks";

export type { GoodMemoryObservabilityConfig, GoodMemoryScopeDigest, GoodMemoryTraceAttributeValue, GoodMemoryTraceLink, GoodMemoryTraceRedaction, GoodMemoryTraceSink, GoodMemoryTraceSpan, GoodMemoryTraceSpanName, GoodMemoryTraceSpanStatus, } from "./observability/contracts";
export type { ModelTokenUsage, ModelUsageAttempt, ModelUsageCompleteness, ModelUsageOperation, ModelUsageSink, } from "./provider/model-usage";
export type { RuntimeArchiveStore, RuntimeArchiveStoreConfig, RuntimeContextService, RuntimeContextServiceConfig, RuntimeContextState, RuntimeEndSessionArchiveOptions, RuntimeEndSessionOptions, RuntimeRecallSnapshot, SessionJournalPatch, SessionSummaryInput, WorkingMemoryPatch, } from "./runtime/public";

@@ -53,0 +58,0 @@ export { createRuntimeArchiveStore, createRuntimeContextService, } from "./runtime/public";

@@ -1,2 +0,3 @@

import type { LanguageAdapter } from "./contracts";
export declare function createChineseLanguageAdapter(): LanguageAdapter;
import type { LanguagePack } from "./contracts";
import { type ChineseScript } from "./chineseSemantics";
export declare function createChineseLanguagePack(script: ChineseScript): LanguagePack;

@@ -0,6 +1,12 @@

import type { MemoryCandidate } from "../domain/memoryCandidate";
import type { FeedbackKind } from "../domain/records";
import type { MemoryCandidate } from "../domain/memoryCandidate";
export type LocaleResolutionSource = "explicit" | "detected" | "default";
export type LanguageDetectionStrength = "distinctive" | "compatible" | "none";
export type LanguageDetectionMode = "auto" | "default_only";
export interface LanguageDetectionInput {
texts: string[];
}
export interface LanguageCandidateExtractionInput {
messages: Array<{
analysis?: LanguageContentAnalysis;
role: string;

@@ -13,11 +19,198 @@ content: string;

}
export interface LanguageAdapter {
id: string;
supportsLocale(locale: string): boolean;
splitClauses(text: string): string[];
export interface LanguageQueryAnalysis {
actionDriving: boolean;
after: boolean;
aggregateCount: boolean;
answerComposition: boolean;
assistantEvidenceRecall: boolean;
before: boolean;
blocker: boolean;
change: boolean;
continuation: boolean;
current: boolean;
directFactualLookup: boolean;
exhaustiveList: boolean;
factConfirmation: boolean;
focus: boolean;
guidanceSeeking: boolean;
history: boolean;
openLoop: boolean;
procedural: boolean;
projectState: boolean;
recommendationStyle: boolean;
relation: boolean;
referenceSeeking: boolean;
role: boolean;
userGroundedEventOrder: boolean;
}
export interface LanguageSourceOfTruthDirective {
currentPointer: string;
supersededPointer?: string;
}
export interface LanguageContentAnalysis {
assistantAcknowledgement: boolean;
assistantContinuity: boolean;
blockerFact: boolean;
correctionCue: boolean;
durableCue: boolean;
factPolarity: "positive" | "negative" | "unknown";
feedbackKind: FeedbackKind;
focusFact: boolean;
openLoopFact: boolean;
personalEvidence: boolean;
preferenceEvidence: boolean;
projectStateFact: boolean;
roleFact: boolean;
sensitiveCredential: boolean;
sourceOfTruthDirective?: LanguageSourceOfTruthDirective;
unresolved: boolean;
}
export interface LanguageBehavioralRuleAnalysis {
analogyText?: string;
argumentOrder?: string[];
backupRequested?: boolean;
commandName?: string;
conciseComputation?: {
base: number;
kind: "percentage";
percentage: number;
} | {
kind: "circle_circumference";
radius: number;
} | {
kind: "iso_datetime_command";
};
comparison?: {
field?: string;
operator?: "<" | "<=" | "=" | ">" | ">=";
value?: string;
};
directoryRestriction?: {
forbiddenRoot?: string;
safeTemplate?: string;
userHomeRequired?: boolean;
};
distrustRouting?: {
preferredAlternative?: string;
target: string;
};
exactAction?: string;
filetypeReplacement?: {
forbidden: string;
preferred: string;
};
firstActionName?: string;
forbiddenFragments?: string[];
formatRule: boolean;
formatPrefix?: string;
formatSurface?: {
prefixes: string[];
suffixes: string[];
};
formatSuffix?: string;
generalRule: boolean;
guard?: {
allowedStates: string[];
check: string;
subject?: string;
};
hostAction?: {
compression?: string;
destination?: string;
flags?: string[];
mode?: string;
owner?: string;
permissions?: string;
sources?: string[];
tag?: string;
verb?: string;
};
negativeRule: boolean;
namedTarget?: string;
pathBase?: string;
preferredAlternatives?: string[];
preferredFragments?: string[];
protocolReplacement?: {
forbiddenUrl: string;
preferredUrl: string;
};
protocolRewrite?: {
template?: string;
};
requiredFragments?: string[];
responseStyle?: "brief" | "bullets";
semanticCues?: Array<"analogy" | "api" | "argument_order" | "brevity" | "command" | "failure" | "filetype" | "format" | "inhibition_replacement" | "operation" | "path" | "permission_failure" | "precondition" | "safe_fallback" | "style" | "symbolic" | "timeout" | "unsafe" | "url" | "voice">;
structuredTerms?: string[];
triggerPhrases?: string[];
warningSignal?: boolean;
}
export type LanguageTemporalExpression = {
kind: "absolute";
raw: string;
calendar: {
day?: number;
month?: number;
year: number;
};
} | {
kind: "absolute";
raw: string;
iso: string;
} | {
kind: "relative";
raw: string;
offset: number;
unit: "day" | "week" | "month" | "quarter" | "year";
} | {
kind: "relative";
raw: string;
month: number;
occurrence: "latest" | "strictly_before";
unit: "month";
} | {
kind: "range";
raw: string;
end?: string;
start?: string;
};
export interface LanguageEntityMention {
kind?: "identifier" | "location" | "organization" | "person" | "term";
normalized: string;
surface: string;
}
export interface LanguageEntityCandidateInput {
aliases: readonly string[];
canonicalKey: string;
documentTexts: readonly string[];
}
export type LanguageRenderKey = "active_context" | "additional_project_state" | "archive" | "archive_recap" | "artifact_spills" | "behavioral_controls_available" | "behavioral_exact_surface" | "behavioral_example" | "behavioral_observed_outcome" | "behavioral_raw_response_control" | "behavioral_relevant_prior_examples" | "behavioral_safe_corrected_move" | "behavioral_situation" | "behavioral_successful_move" | "canonical_pattern" | "correction" | "current_goal" | "current_projects" | "current_state" | "constraints" | "deferred_follow_up" | "developer_memory_notes" | "durable_memory" | "earlier_messages_compacted" | "episode" | "episode_assistant_follow_through_captured" | "episode_assistant_follow_through_on" | "episode_assistant_substantive_continuity_captured" | "episode_conversation_covered" | "episode_item" | "evidence" | "evidence_entry" | "evidence_note" | "experiences" | "excerpt" | "fact" | "fact_item" | "feedback" | "file_evidence" | "file_or_function" | "goals" | "guidance" | "immediate_next_steps" | "installed_host_claude_memory_protocol" | "installed_host_context_tool_protocol" | "installed_host_injected_context_protocol" | "installed_host_intro" | "installed_host_projection_protocol" | "installed_host_protocol_heading" | "installed_host_record_tools_protocol" | "installed_host_remember_protocol" | "instruction" | "journal" | "key_decisions" | "key_files" | "language_label" | "learning_proposals" | "lineage" | "location" | "memory_index" | "metadata" | "name" | "none" | "organization" | "claim" | "actor" | "open_loops" | "omitted_sections" | "preference" | "playbook_title" | "procedural_memory" | "profile" | "progressive_detail_instruction" | "progressive_detail_instruction_compact" | "progressive_recall" | "prompt_snippet_title" | "promotions" | "procedure" | "recent_decisions" | "recent_worklog" | "reference" | "reference_item" | "referenced_artifacts" | "relation_label" | "role_label" | "scope" | "session_archive_item" | "session_ended_without_summary" | "session_handoff" | "session_memory" | "session_resume_query" | "session_start_query" | "skill_snippet_title" | "tool_result" | "temporal_status" | "summary" | "detail_tokens" | "omitted_records" | "record_kind" | "record_ref" | "temporary_decision" | "timezone" | "verification" | "user_memory_context" | "user_memory" | "undated" | "use_when" | "default_label" | "workflow" | "working_memory" | "why" | "workspace_query_anchor";
export interface LanguageRenderInput {
key: LanguageRenderKey;
values?: Record<string, number | string>;
}
export interface LanguagePack {
readonly analyzerVersion: string;
readonly apiVersion: 1;
readonly compatibilityGroup: string;
readonly defaultLocale: string;
readonly id: string;
readonly locales: readonly string[];
detect(input: LanguageDetectionInput): LanguageDetectionStrength;
normalizeForEquality(text: string): string;
tokenize(text: string, options?: {
tokenizeForScoring(text: string, mode: "bm25" | "overlap", options?: {
excludeStopwords?: boolean;
}): string[];
buildSearchTerms(text: string): string[];
splitClauses(text: string): string[];
splitSentences(text: string): string[];
decomposeQuery(text: string): string[];
analyzeBehavioralRule(text: string): LanguageBehavioralRuleAnalysis;
analyzeQuery(text: string): LanguageQueryAnalysis;
analyzeContent(text: string): LanguageContentAnalysis;
parseTemporalExpressions(text: string): LanguageTemporalExpression[];
extractEntityMentions(text: string): LanguageEntityMention[];
matchesEntityAlias(query: string, alias: string): boolean;
acceptsEntityCandidate(input: LanguageEntityCandidateInput): boolean;
extractCandidates(input: LanguageCandidateExtractionInput): MemoryCandidate[];
render(input: LanguageRenderInput): string;
}

@@ -32,14 +225,35 @@ export interface LocaleDetectorInput {

defaultLocale?: string;
detection?: "auto" | "explicit_first";
detection?: LanguageDetectionMode;
detector?: LocaleDetector;
adapters?: LanguageAdapter[];
detectorVersion?: string;
packs?: readonly LanguagePack[];
}
export interface LanguageAnalyzerManifestPack {
readonly analyzerVersion: string;
readonly apiVersion: 1;
readonly compatibilityGroup: string;
readonly defaultLocale: string;
readonly id: string;
readonly locales: readonly string[];
}
export interface LanguageAnalyzerManifest {
readonly defaultLocale: string;
readonly detection: LanguageDetectionMode;
readonly detectorVersion?: string;
readonly packs: readonly LanguageAnalyzerManifestPack[];
readonly persistable: boolean;
readonly resolutionOrder: readonly string[];
readonly resolverVersion: string;
readonly schemaVersion: 1;
}
export interface ResolvedLanguageContext {
analysisMode: "rules-only";
compatibilityGroup: string;
languagePackId: string;
languagePackVersion: string;
locale: string;
localeSource: LocaleResolutionSource;
adapter: LanguageAdapter;
adapterId: string;
analysisMode: "rules-only";
}
export interface LanguageService {
getAnalyzerManifest(): LanguageAnalyzerManifest;
resolveFromMessages(input: {

@@ -56,2 +270,3 @@ locale?: string;

}): ResolvedLanguageContext;
analyzerVersion(context: ResolvedLanguageContext | string): string;
normalizeForEquality(text: string, context: ResolvedLanguageContext | string): string;

@@ -61,3 +276,15 @@ tokenize(text: string, context: ResolvedLanguageContext | string, options?: {

}): string[];
buildSearchTerms(text: string, context: ResolvedLanguageContext | string): string[];
splitClauses(text: string, context: ResolvedLanguageContext | string): string[];
splitSentences(text: string, context: ResolvedLanguageContext | string): string[];
decomposeQuery(text: string, context: ResolvedLanguageContext | string): string[];
analyzeBehavioralRule(text: string, context: ResolvedLanguageContext | string): LanguageBehavioralRuleAnalysis;
analyzeQuery(text: string, context: ResolvedLanguageContext | string): LanguageQueryAnalysis;
analyzeContent(text: string, context: ResolvedLanguageContext | string): LanguageContentAnalysis;
parseTemporalExpressions(text: string, context: ResolvedLanguageContext | string): LanguageTemporalExpression[];
extractEntityMentions(text: string, context: ResolvedLanguageContext | string): LanguageEntityMention[];
matchesEntityAlias(query: string, alias: string, context: ResolvedLanguageContext | string): boolean;
acceptsEntityCandidate(input: LanguageEntityCandidateInput, context: ResolvedLanguageContext | string): boolean;
extractCandidates(input: LanguageCandidateExtractionInput, context: ResolvedLanguageContext | string): MemoryCandidate[];
render(input: LanguageRenderInput, context: ResolvedLanguageContext | string): string;
tokenOverlap(left: string, right: string, context: ResolvedLanguageContext | string, options?: {

@@ -64,0 +291,0 @@ excludeStopwords?: boolean;

@@ -1,2 +0,2 @@

import type { LanguageAdapter } from "./contracts";
export declare function createEnglishLanguageAdapter(): LanguageAdapter;
import type { LanguagePack } from "./contracts";
export declare function createEnglishLanguagePack(): LanguagePack;

@@ -1,2 +0,2 @@

import type { LanguageAdapter } from "./contracts";
import type { LanguagePack } from "./contracts";
export declare function normalizeUnicodeForEquality(value: string): string;

@@ -6,2 +6,2 @@ export declare function containsHanScript(value: string): boolean;

export declare function splitClausesGeneric(content: string): string[];
export declare function createGenericLanguageAdapter(): LanguageAdapter;
export declare function createNeutralLanguagePack(): LanguagePack;

@@ -1,5 +0,9 @@

export type { LanguageAdapter, LanguageCandidateExtractionInput, LanguageConfig, LanguageService, LocaleDetector, LocaleDetectorInput, LocaleResolutionSource, ResolvedLanguageContext, } from "./contracts";
export { createChineseLanguageAdapter } from "./chinese";
export { createEnglishLanguageAdapter } from "./english";
export { createGenericLanguageAdapter } from "./generic";
export type { LanguageCandidateExtractionInput, LanguageAnalyzerManifest, LanguageAnalyzerManifestPack, LanguageBehavioralRuleAnalysis, LanguageConfig, LanguageContentAnalysis, LanguageDetectionInput, LanguageDetectionMode, LanguageDetectionStrength, LanguageEntityCandidateInput, LanguageEntityMention, LanguagePack, LanguageQueryAnalysis, LanguageRenderInput, LanguageRenderKey, LanguageService, LanguageSourceOfTruthDirective, LanguageTemporalExpression, LocaleDetector, LocaleDetectorInput, LocaleResolutionSource, ResolvedLanguageContext, } from "./contracts";
export { createChineseLanguagePack } from "./chinese";
export { createEnglishLanguagePack } from "./english";
export { createFrenchLanguagePack } from "./french";
export { createNeutralLanguagePack } from "./generic";
export { createJapaneseLanguagePack } from "./japanese";
export { createKoreanLanguagePack } from "./korean";
export { createLanguageService } from "./service";
export { createSpanishLanguagePack } from "./spanish";
import type { EmbeddingAdapter } from "../embedding/contracts";
import type { MemoryScope } from "../domain/scope";
import { type LanguageService } from "../language";
import type { LanguageService } from "../language";
import type { MaintenanceRepositoryPort, MaintenanceVectorPort } from "../storage/ports";
export type MaintenanceJobName = "projectionRepair" | "dedupe" | "contradiction" | "qualityRepair" | "consolidation" | "embeddingRepair" | "ttlExpiry";
export type MaintenanceJobName = "projectionMigration" | "projectionRepair" | "dedupe" | "contradiction" | "qualityRepair" | "consolidation" | "embeddingRepair" | "ttlExpiry";
export interface MaintenanceRunnerConfig {

@@ -12,2 +12,8 @@ embedding?: EmbeddingAdapter;

};
projectionMigration?: {
ensureScopeIndexed(scope: MemoryScope): Promise<{
complete: boolean;
indexedSources: number;
}>;
};
repositories: MaintenanceRepositoryPort & {

@@ -14,0 +20,0 @@ vectorIndex?: MaintenanceVectorPort | null;

@@ -41,3 +41,5 @@ export type GoodMemoryTraceSpanName = "memory.remember" | "memory.recall" | "memory.build_context" | "memory.revise" | "memory.feedback" | "memory.forget" | "memory.export" | "memory.delete_all" | "memory.policy.block" | "runtime.session.start" | "runtime.session.end" | "writeback.job.enqueue" | "writeback.job.commit" | "maintenance.run";

scopeDigestSecret?: string;
modelUsageSink?: ModelUsageSink;
traceSink?: GoodMemoryTraceSink;
}
import type { ModelUsageSink } from "../provider/model-usage";
import type { GoodMemory, RecallInput, RecallResult } from "../api/contracts";
import type { MemoryScope } from "../domain/scope";
import type { LanguageService } from "../language";
export type ProgressiveRecordKind = "profile" | "preference" | "fact" | "feedback" | "episode" | "evidence" | "experience" | "reference" | "archive" | "proposal" | "promotion" | "runtime-journal" | "runtime-spill" | "writeback-event";

@@ -18,3 +19,5 @@ export type GoodMemoryRecordRef = `gmrec:v1:${string}:${ProgressiveRecordKind}:${string}`;

}
type ProgressiveLanguagePort = Pick<LanguageService, "render" | "resolveFromText" | "tokenize">;
export interface CreateProgressiveRecallServiceInput {
language?: ProgressiveLanguagePort;
memory: Pick<GoodMemory, "recall"> | ProgressiveRecallMemory;

@@ -28,2 +31,3 @@ scopeDigestSecret: string;

query?: string;
locale?: RecallInput["locale"];
includeRuntime?: boolean;

@@ -46,2 +50,3 @@ limit?: number;

generatedAt: string;
locale?: string;
query?: string;

@@ -61,2 +66,3 @@ records: ProgressiveRecallIndexRecord[];

buckets: ProgressiveRecallTimelineBucket[];
locale?: string;
scopeDigest: string;

@@ -107,1 +113,2 @@ totalRecordCount: number;

export declare function createProgressiveRecallService(input: CreateProgressiveRecallServiceInput): ProgressiveRecallService;
export {};

@@ -6,2 +6,3 @@ import type { FetchFunction } from "@ai-sdk/provider-utils";

import type { ModelProviderId } from "./model-provider";
import type { ModelTokenUsage, ModelUsageSink } from "./model-usage";
export interface AISDKModelConfig {

@@ -13,4 +14,17 @@ provider: ModelProviderId;

}
export type OpenAICompatibleReasoningEffort = "low" | "medium" | "high";
export type OpenAICompatibleObjectResponseFormat = "json_object" | "json_schema";
type OpenAICompatibleResponseFormat = {
type: "json_object";
} | {
type: "json_schema";
json_schema: {
name: "structured_response";
strict: false;
schema: unknown;
};
};
interface EmbeddingAdapterDependencies {
embedMany?: typeof embedMany;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;

@@ -27,2 +41,3 @@ resolveEmbeddingModel?: typeof resolveAISDKEmbeddingModel;

export declare const DEFAULT_AISDK_EMBEDDING_BATCH_MAX_INPUTS = 256;
export declare const DEFAULT_AISDK_RETRY_LIMIT = 4;
export interface AISDKRetryOptions {

@@ -35,4 +50,11 @@ retryLimit?: number;

export declare function stripThinkingBlocks(value: string): string;
export declare function requestOpenAICompatibleText(input: {
export interface OpenAICompatibleTextResult {
text: string;
usage: ModelTokenUsage | null;
}
interface OpenAICompatibleTextInput {
maxOutputTokens?: number;
model: AISDKModelConfig;
responseFormat?: OpenAICompatibleResponseFormat;
reasoningEffort?: OpenAICompatibleReasoningEffort;
system?: string;

@@ -44,4 +66,7 @@ prompt: string;

timeoutMs?: number;
}): Promise<string>;
}
export declare function requestOpenAICompatibleText(input: OpenAICompatibleTextInput): Promise<string>;
export declare function requestOpenAICompatibleTextResult(input: OpenAICompatibleTextInput): Promise<OpenAICompatibleTextResult>;
export declare function requestOpenAICompatibleObject<T>(input: {
maxOutputTokens?: number;
model: AISDKModelConfig;

@@ -51,2 +76,3 @@ schema: z.ZodType<T>;

prompt: string;
reasoningEffort?: OpenAICompatibleReasoningEffort;
temperature?: number;

@@ -57,3 +83,22 @@ fetch?: FetchLike;

normalizePayload?: (payload: unknown) => unknown;
responseFormat?: OpenAICompatibleObjectResponseFormat;
}): Promise<T>;
export declare function requestOpenAICompatibleObjectResult<T>(input: {
fetch?: FetchLike;
maxOutputTokens?: number;
model: AISDKModelConfig;
normalizePayload?: (payload: unknown) => unknown;
onUsage?: (usage: ModelTokenUsage | null) => void;
prompt: string;
reasoningEffort?: OpenAICompatibleReasoningEffort;
responseFormat?: OpenAICompatibleObjectResponseFormat;
schema: z.ZodType<T>;
signal?: AbortSignal;
system?: string;
temperature?: number;
timeoutMs?: number;
}): Promise<{
object: T;
usage: ModelTokenUsage | null;
}>;
export declare function parseAISDKModelConfigFromEnv(prefix: string): AISDKModelConfig | null;

@@ -63,2 +108,5 @@ export declare function resolveAISDKModel(config: AISDKModelConfig): LanguageModel;

export declare function createAISDKEmbeddingAdapter(input: {
batchMaxConcurrency?: number;
batchMaxInputs?: number;
batchMaxUtf8Bytes?: number;
model: AISDKModelConfig;

@@ -65,0 +113,0 @@ dependencies?: EmbeddingAdapterDependencies;

import type { RecallRouterAssistant } from "../recall/assistant";
import type { RecallPlanAssistant } from "../recall/recallPlan";
import type { Reranker } from "../recall/reranker";
import type { MemoryExtractionContext, MemoryExtractionInput, MemoryExtractor } from "../remember/candidates";
import type { EmbeddingAdapter } from "../embedding/contracts";
import type { AISDKModelConfig } from "./ai-sdk-runtime";
import type { AISDKModelConfig, AISDKRetryOptions, OpenAICompatibleObjectResponseFormat, OpenAICompatibleReasoningEffort } from "./ai-sdk-runtime";
import type { MemoryExtractionOutputProtocol } from "./memory-extractor";
import type { RecallPlanAssistantDependencies } from "./recall-plan-assistant";
import type { ListwiseRerankerDependencies, PointwiseRerankerDependencies } from "./reranker";
import type { ModelProviderId, ProviderRuntimeMetadata, RuntimeTargetDescriptor } from "./contracts";
import type { ModelUsageSink } from "./model-usage";
interface ProviderMemoryExtractorFactory {
(input: {
dependencies?: ProviderRequestDependencies;
maxOutputTokens?: number;
model: AISDKModelConfig;
outputProtocol?: MemoryExtractionOutputProtocol;
promptBuilder?: (input: MemoryExtractionInput, context?: MemoryExtractionContext) => string;
reasoningEffort?: OpenAICompatibleReasoningEffort;
responseFormat?: OpenAICompatibleObjectResponseFormat;
system?: string;
temperature?: number;
}): MemoryExtractor;

@@ -18,2 +27,5 @@ }

(input: {
batchMaxConcurrency?: number;
batchMaxInputs?: number;
batchMaxUtf8Bytes?: number;
dependencies?: ProviderRequestDependencies;

@@ -31,6 +43,17 @@ model: AISDKModelConfig;

}
interface ProviderRecallPlanAssistantFactory {
(input: {
dependencies?: RecallPlanAssistantDependencies;
maxOutputTokens?: number;
model: AISDKModelConfig;
system?: string;
temperature?: number;
}): RecallPlanAssistant;
}
interface ProviderRerankerFactory {
(input: {
dependencies?: PointwiseRerankerDependencies;
maxOutputTokens?: number;
model: AISDKModelConfig;
temperature?: number;
}): Reranker;

@@ -41,7 +64,12 @@ }

dependencies?: ListwiseRerankerDependencies;
maxOutputTokens?: number;
model: AISDKModelConfig;
reasoningEffort?: OpenAICompatibleReasoningEffort;
temperature?: number;
}): Reranker;
}
export interface ProviderRequestDependencies {
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;
retryOptions?: AISDKRetryOptions;
}

@@ -60,7 +88,14 @@ export interface ModelProviderDescriptorInput {

export declare function createProviderMemoryExtractor(input: {
maxOutputTokens?: number;
model: AISDKModelConfig;
outputProtocol?: MemoryExtractionOutputProtocol;
promptBuilder?: (input: MemoryExtractionInput, context?: MemoryExtractionContext) => string;
system?: string;
createMemoryExtractor?: ProviderMemoryExtractorFactory;
modelUsageSink?: ModelUsageSink;
reasoningEffort?: OpenAICompatibleReasoningEffort;
responseFormat?: OpenAICompatibleObjectResponseFormat;
requestTimeoutMs?: number;
retryLimit?: number;
temperature?: number;
}): MemoryExtractor;

@@ -71,8 +106,20 @@ export declare function createProviderConversationalMemoryExtractor(input: {

createMemoryExtractor?: ProviderMemoryExtractorFactory;
maxOutputTokens?: number;
modelUsageSink?: ModelUsageSink;
outputProtocol?: MemoryExtractionOutputProtocol;
reasoningEffort?: OpenAICompatibleReasoningEffort;
responseFormat?: OpenAICompatibleObjectResponseFormat;
requestTimeoutMs?: number;
retryLimit?: number;
temperature?: number;
}): MemoryExtractor;
export declare function createProviderEmbeddingAdapter(input: {
batchMaxConcurrency?: number;
batchMaxInputs?: number;
batchMaxUtf8Bytes?: number;
model: AISDKModelConfig;
createEmbeddingAdapter?: ProviderEmbeddingAdapterFactory;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;
retryLimit?: number;
}): EmbeddingAdapter;

@@ -82,2 +129,3 @@ export declare function createProviderRecallRouter(input: {

createRecallRouter?: ProviderRecallRouterFactory;
modelUsageSink?: ModelUsageSink;
planSystem?: string;

@@ -87,8 +135,21 @@ requestTimeoutMs?: number;

}): RecallRouterAssistant;
export declare function createProviderRecallPlanAssistant(input: {
createRecallPlanAssistant?: ProviderRecallPlanAssistantFactory;
maxOutputTokens?: number;
model: AISDKModelConfig;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;
retryLimit?: number;
system?: string;
temperature?: number;
}): RecallPlanAssistant;
export declare function createProviderPointwiseReranker(input: {
createReranker?: ProviderRerankerFactory;
maxConcurrency?: number;
maxOutputTokens?: number;
model: AISDKModelConfig;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;
retryLimit?: number;
temperature?: number;
}): Reranker;

@@ -98,7 +159,11 @@ export declare function createProviderListwiseReranker(input: {

maxConcurrency?: number;
maxOutputTokens?: number;
model: AISDKModelConfig;
modelUsageSink?: ModelUsageSink;
reasoningEffort?: OpenAICompatibleReasoningEffort;
requestTimeoutMs?: number;
retryLimit?: number;
temperature?: number;
}): Reranker;
export declare function buildProviderRequestDependencies(requestTimeoutMs: number | undefined): ProviderRequestDependencies | undefined;
export declare function buildProviderRequestDependencies(requestTimeoutMs: number | undefined, modelUsageSink?: ModelUsageSink, retryLimit?: number): ProviderRequestDependencies | undefined;
export {};
import { generateObject } from "ai";
import { z } from "zod";
import { resolveAISDKModel } from "./ai-sdk-runtime";
import type { AISDKModelConfig, AISDKRetryOptions, FetchLike } from "./ai-sdk-runtime";
import type { AISDKModelConfig, AISDKRetryOptions, FetchLike, OpenAICompatibleObjectResponseFormat, OpenAICompatibleReasoningEffort } from "./ai-sdk-runtime";
import type { ModelUsageSink } from "./model-usage";
import type { MemoryExtractionContext, MemoryExtractionInput, MemoryExtractor } from "../remember/candidates";

@@ -9,2 +10,3 @@ interface MemoryExtractorDependencies {

generateObject?: typeof generateObject;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;

@@ -14,2 +16,3 @@ resolveModel?: typeof resolveAISDKModel;

}
export declare const MEMORY_EXTRACTION_SYSTEM_PROMPT: string;
export declare const memoryExtractionResultSchema: z.ZodObject<{

@@ -33,2 +36,3 @@ candidates: z.ZodArray<z.ZodObject<{

sourceMessageIndex: z.ZodNumber;
sourceMessageIndexes: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
sourceRole: z.ZodString;

@@ -38,9 +42,23 @@ metadata: z.ZodOptional<z.ZodObject<{

attributes: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>>>;
category: z.ZodOptional<z.ZodOptional<z.ZodEnum<{
project: "project";
technical: "technical";
personal: "personal";
relationship: "relationship";
event: "event";
}>>>;
category: z.ZodOptional<z.ZodOptional<z.ZodString>>;
claim: z.ZodOptional<z.ZodOptional<z.ZodObject<{
confidence: z.ZodOptional<z.ZodNumber>;
modality: z.ZodOptional<z.ZodEnum<{
asserted: "asserted";
planned: "planned";
attempted: "attempted";
completed: "completed";
unknown: "unknown";
}>>;
objectEntity: z.ZodOptional<z.ZodString>;
objectText: z.ZodString;
polarity: z.ZodOptional<z.ZodEnum<{
positive: "positive";
negative: "negative";
}>>;
predicateKey: z.ZodString;
validFrom: z.ZodOptional<z.ZodString>;
validUntil: z.ZodOptional<z.ZodString>;
}, z.core.$strip>>>;
contextualDescriptor: z.ZodOptional<z.ZodOptional<z.ZodString>>;
factKind: z.ZodOptional<z.ZodOptional<z.ZodEnum<{

@@ -94,5 +112,94 @@ blocker: "blocker";

}, z.core.$strip>;
export declare const compactConversationalMemoryExtractionResultSchema: z.ZodObject<{
c: z.ZodArray<z.ZodObject<{
c: z.ZodString;
e: z.ZodOptional<z.ZodEnum<{
explicit: "explicit";
inferred: "inferred";
}>>;
k: z.ZodOptional<z.ZodEnum<{
reference: "reference";
preference: "preference";
feedback: "feedback";
profile: "profile";
fact: "fact";
episode: "episode";
noise: "noise";
}>>;
m: z.ZodOptional<z.ZodObject<{
a: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>>;
ap: z.ZodOptional<z.ZodString>;
ca: z.ZodOptional<z.ZodString>;
d: z.ZodOptional<z.ZodString>;
fb: z.ZodOptional<z.ZodEnum<{
do: "do";
dont: "dont";
prefer: "prefer";
validated_pattern: "validated_pattern";
}>>;
fk: z.ZodOptional<z.ZodEnum<{
blocker: "blocker";
open_loop: "open_loop";
role_update: "role_update";
focus_update: "focus_update";
project_state: "project_state";
generic_project: "generic_project";
}>>;
pc: z.ZodOptional<z.ZodString>;
pf: z.ZodOptional<z.ZodEnum<{
name: "name";
role: "role";
organization: "organization";
location: "location";
timezone: "timezone";
languagePreference: "languagePreference";
currentProject: "currentProject";
}>>;
pv: z.ZodOptional<z.ZodString>;
q: z.ZodOptional<z.ZodObject<{
c: z.ZodOptional<z.ZodNumber>;
f: z.ZodOptional<z.ZodString>;
m: z.ZodOptional<z.ZodEnum<{
asserted: "asserted";
planned: "planned";
attempted: "attempted";
completed: "completed";
unknown: "unknown";
}>>;
n: z.ZodOptional<z.ZodLiteral<true>>;
o: z.ZodString;
oe: z.ZodOptional<z.ZodString>;
p: z.ZodString;
u: z.ZodOptional<z.ZodString>;
}, z.core.$strip>>;
rk: z.ZodOptional<z.ZodEnum<{
source_of_truth: "source_of_truth";
runbook: "runbook";
doc: "doc";
dashboard: "dashboard";
tracker: "tracker";
}>>;
rp: z.ZodOptional<z.ZodString>;
rt: z.ZodOptional<z.ZodString>;
sk: z.ZodOptional<z.ZodEnum<{
project: "project";
identity: "identity";
runtime: "runtime";
reference: "reference";
preference: "preference";
}>>;
sp: z.ZodOptional<z.ZodString>;
t: z.ZodOptional<z.ZodArray<z.ZodString>>;
u: z.ZodOptional<z.ZodString>;
}, z.core.$strip>>;
s: z.ZodNumber;
ss: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
}, z.core.$strip>>;
i: z.ZodNumber;
}, z.core.$strip>;
export type MemoryExtractionOutputProtocol = "canonical-v1" | "compact-conversational-v1";
export declare function normalizeMemoryExtractionPayload(payload: unknown): unknown;
export declare function buildMemoryExtractionPrompt(input: MemoryExtractionInput): string;
export declare const CONVERSATIONAL_MEMORY_EXTRACTION_SYSTEM_PROMPT: string;
export declare const COMPACT_CONVERSATIONAL_MEMORY_EXTRACTION_SYSTEM_PROMPT: string;
export interface ConversationalExtractionOptions {

@@ -103,8 +210,14 @@ contextualDescriptor?: boolean;

export declare function buildConversationalMemoryExtractionPrompt(input: MemoryExtractionInput, options?: ConversationalExtractionOptions): string;
export declare function buildCompactConversationalMemoryExtractionPrompt(input: MemoryExtractionInput, options?: ConversationalExtractionOptions): string;
export declare function createLLMMemoryExtractor(input: {
dependencies?: MemoryExtractorDependencies;
maxOutputTokens?: number;
model: AISDKModelConfig;
outputProtocol?: MemoryExtractionOutputProtocol;
promptBuilder?: (input: MemoryExtractionInput, context?: MemoryExtractionContext) => string;
reasoningEffort?: OpenAICompatibleReasoningEffort;
responseFormat?: OpenAICompatibleObjectResponseFormat;
system?: string;
temperature?: number;
}): MemoryExtractor;
export {};

@@ -7,5 +7,7 @@ import { generateObject } from "ai";

import { resolveAISDKModel } from "./ai-sdk-runtime";
import type { ModelUsageSink } from "./model-usage";
interface RecallRouterDependencies {
fetch?: FetchLike;
generateObject?: typeof generateObject;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;

@@ -12,0 +14,0 @@ resolveModel?: typeof resolveAISDKModel;

import { generateObject } from "ai";
import type { Reranker, RerankerDocument } from "../recall/reranker";
import { resolveAISDKModel } from "./ai-sdk-runtime";
import type { AISDKModelConfig, AISDKRetryOptions, FetchLike } from "./ai-sdk-runtime";
import type { AISDKModelConfig, AISDKRetryOptions, FetchLike, OpenAICompatibleReasoningEffort } from "./ai-sdk-runtime";
import type { ModelUsageSink } from "./model-usage";
export declare const POINTWISE_RERANKER_SYSTEM_PROMPT: string;

@@ -19,2 +20,3 @@ export declare const LISTWISE_RERANKER_SYSTEM_PROMPT: string;

maxConcurrency?: number;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;

@@ -28,2 +30,3 @@ resolveModel?: typeof resolveAISDKModel;

maxConcurrency?: number;
modelUsageSink?: ModelUsageSink;
requestTimeoutMs?: number;

@@ -35,9 +38,14 @@ resolveModel?: typeof resolveAISDKModel;

dependencies?: PointwiseRerankerDependencies;
maxOutputTokens?: number;
model: AISDKModelConfig;
system?: string;
temperature?: number;
}): Reranker;
export declare function createLLMListwiseReranker(input: {
dependencies?: ListwiseRerankerDependencies;
maxOutputTokens?: number;
model: AISDKModelConfig;
reasoningEffort?: OpenAICompatibleReasoningEffort;
system?: string;
temperature?: number;
}): Reranker;
import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";
import type { EvidenceRecord } from "../evidence/contracts";
import type { LanguageService, ResolvedLanguageContext } from "../language";
import type { SessionArchive } from "../domain/evolutionRecords";
import type { RetrievalProfile, RoutingDecision } from "./router";
declare const CONTEXT_RENDER_KEYS: readonly ["active_context", "additional_project_state", "archive", "correction", "current_goal", "current_projects", "current_state", "deferred_follow_up", "developer_memory_notes", "durable_memory", "episode", "episode_item", "evidence", "fact", "fact_item", "feedback", "file_evidence", "goals", "immediate_next_steps", "journal", "key_decisions", "open_loops", "omitted_sections", "preference", "procedural_memory", "profile", "recent_worklog", "reference", "reference_item", "session_archive_item", "tool_result", "verification", "user_memory_context", "working_memory"];
type MemoryPacketRenderKey = (typeof CONTEXT_RENDER_KEYS)[number];
type MemoryPacketRenderLabels = Record<MemoryPacketRenderKey, string>;
export interface MemoryPacket {
locale?: string;
languagePackId?: string;
renderLabels?: MemoryPacketRenderLabels;
profileSummary?: string;

@@ -19,2 +26,5 @@ activeContextSummary?: string;

renderingProfile?: RetrievalProfile;
renderBudget?: {
maxTokens: number;
};
debug?: {

@@ -37,6 +47,14 @@ omittedSections: string[];

durableCandidateOrder?: string[];
maxRenderedTokens?: number;
locale?: string;
language?: LanguageService;
languageContext?: ResolvedLanguageContext;
languagePackId?: string;
renderLabels?: MemoryPacketRenderLabels;
routingDecision?: RoutingDecision;
}
export declare function buildMemoryPacket(input: MemoryPacketInput): MemoryPacket;
export declare function rebuildMemoryPacket(source: MemoryPacket, input: Omit<MemoryPacketInput, "language" | "maxRenderedTokens"> & {
language: LanguageService;
}): MemoryPacket;
export declare function renderMemoryPacket(packet: MemoryPacket, output: "json" | "markdown" | "system_prompt_fragment" | "developer_prompt_fragment", maxTokens?: number, renderingProfileOverride?: RetrievalProfile, options?: {

@@ -49,1 +67,2 @@ suppressDuplicateEvidence?: boolean;

};
export {};

@@ -7,3 +7,3 @@ import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";

import type { SessionArchive } from "../domain/evolutionRecords";
import { type LanguageService } from "../language";
import type { LanguageQueryAnalysis, LanguageService, ResolvedLanguageContext } from "../language";
import type { GoodMemoryPolicyHooks } from "../policy/hooks";

@@ -13,5 +13,9 @@ import type { RecallRepositoryPort, RecallRuntimePort, RecallVectorSearchPort } from "../storage/ports";

import { type MemoryPacket } from "./contextBuilder";
import { type EvidenceLedgerEntry } from "./evidenceLedger";
import { type RecallAssistantInfluence, type RecallRouterAssistant } from "./assistant";
import { type RecallRouterStrategy, type RecallSlot, type RetrievalProfile, type RoutingDecision } from "./router";
import type { RecallRetrievalTrace } from "./retrievalTrace";
import { type RecallPlan, type RecallPlanAssistant } from "./recallPlan";
import type { GeneralizedFusionChannel } from "./generalizedFusion";
import type { FactSelector } from "./generalizedSelection";
import type { RecallProjectionSearchPort } from "./projections/contracts";

@@ -27,2 +31,15 @@ export interface RecallInput {

rerank?: boolean;
/** Request-local plan shared by API orchestration and each retrieval hop. */
recallPlan?: RecallPlan;
/** Internal request-local language context; public callers should omit it. */
languageContext?: ResolvedLanguageContext;
/** Internal request-local query analysis; public callers should omit it. */
queryAnalysis?: LanguageQueryAnalysis;
/**
* Optional per-call temporal anchor (ISO-8601). When set to a parseable
* timestamp it replaces the config clock for this recall: plan resolution,
* temporal claim selection, document visibility, and freshness all anchor
* to it. Invalid values fall back to the config clock.
*/
referenceTime?: string;
}

@@ -53,3 +70,3 @@ export interface RecallHit {

semanticScore?: number;
fallback: "none" | "same_slot_unique_candidate" | "zero_retrieval_lexical" | "semantic_union" | "generalized_fusion";
fallback: "none" | "same_slot_unique_candidate" | "zero_retrieval_lexical" | "cross_session_lexical_bridge" | "semantic_union" | "generalized_fusion";
evidenceIds?: string[];

@@ -65,2 +82,3 @@ }

evidence: EvidenceRecord[];
evidenceLedger?: EvidenceLedgerEntry[];
episodes: EpisodeMemory[];

@@ -81,3 +99,4 @@ workingMemory: WorkingMemorySnapshot | null;

localeSource?: "explicit" | "detected" | "default";
adapterId?: string;
languagePackId?: string;
languagePackVersion?: string;
analysisMode?: "rules-only";

@@ -94,2 +113,8 @@ retrievalTrace?: RecallRetrievalTrace;

export interface RecallGeneralizedFusionConfig {
channels?: readonly GeneralizedFusionChannel[];
contentLaneRecords?: {
episodes?: number;
references?: number;
sessionArchives?: number;
};
maxCandidates?: number;

@@ -101,9 +126,8 @@ maxTotalFacts?: number;

export declare function resolveGeneralizedFusionBudget(input: {
aggregateQuery?: boolean;
base: RecallGeneralizedFusionConfig;
contentTermCount: number;
plan: RecallPlan;
}): {
expanded: boolean;
maxCandidates: number | undefined;
maxTotalFacts: number | undefined;
maxCandidates: number;
maxTotalFacts: number;
};

@@ -113,2 +137,4 @@ export interface RecallEngineConfig {

embedding?: EmbeddingAdapter;
/** Instance-scoped internal override used only by repo-local historical evals. */
factSelector?: FactSelector;
bm25Ranking?: boolean;

@@ -128,2 +154,3 @@ generalizedFusion?: RecallGeneralizedFusionConfig;

projectionIndex?: RecallProjectionSearchPort;
recallPlanner?: RecallPlanAssistant;
referenceTime?: () => string;

@@ -130,0 +157,0 @@ }

@@ -18,3 +18,3 @@ import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";

};
export declare function buildEvidenceLinkIndex(evidence: EvidenceRecord[]): EvidenceLinkIndex;
export declare function buildEvidenceLinkIndex(evidence: EvidenceRecord[], ambiguousSourceMemoryIds?: ReadonlySet<string>): EvidenceLinkIndex;
export declare function attachEvidenceIdsToCandidateTraces(traces: RecallCandidateTrace[], evidenceIndex: EvidenceLinkIndex): RecallCandidateTrace[];

@@ -21,0 +21,0 @@ export declare function buildHits(input: {

import type { RecallCandidateTrace } from "./engine";
import type { GeneralizedFusionCandidate, GeneralizedFusionSourceCollection } from "./generalizedFusion";
export declare function isGeneralizedCandidateTraceEligible(trace: RecallCandidateTrace | undefined): trace is RecallCandidateTrace;
export declare function admitGeneralizedRecords<T>(input: {

@@ -4,0 +5,0 @@ candidates: readonly GeneralizedFusionCandidate[];

@@ -1,3 +0,5 @@

import type { EntityProjection, RecallIndexDocument, RecallProjectionSourceCollection } from "./projections/contracts";
export type GeneralizedFusionChannel = "lexical" | "dense" | "entity";
import type { LanguageEntityCandidateInput } from "../language";
import type { ClaimProjection, EntityProjection, RecallIndexDocument, RecallProjectionSourceCollection } from "./projections/contracts";
import type { RecallPlan } from "./recallPlan";
export type GeneralizedFusionChannel = "lexical" | "dense" | "entity" | "temporal" | "relation";
export type GeneralizedFusionSourceCollection = "facts" | "references" | "episodes" | "session_archives";

@@ -28,4 +30,7 @@ export interface DenseFusionCandidate {

export interface GeneralizedFusionInput {
channels?: readonly GeneralizedFusionChannel[];
claims?: readonly ClaimProjection[];
query: string;
documents: readonly RecallIndexDocument[];
documentSetComplete?: boolean;
entities: readonly EntityProjection[];

@@ -35,9 +40,13 @@ denseCandidates?: readonly DenseFusionCandidate[];

maxEntityMemoryFrequency?: number;
acceptsEntityCandidate: (input: LanguageEntityCandidateInput) => boolean;
matchesEntityAlias: (query: string, alias: string) => boolean;
minRelativeStrength?: number;
plan?: RecallPlan;
referenceTime?: string;
rrfK?: number;
tokenize?: (text: string) => string[];
tokenize: (text: string) => string[];
}
export declare const DEFAULT_GENERALIZED_FUSION_RRF_K = 60;
export declare const DEFAULT_GENERALIZED_FUSION_MIN_RELATIVE_STRENGTH = 0.35;
export declare function claimProjectionGroupKey(claim: Pick<ClaimProjection, "predicateKey" | "scopeKey" | "subjectEntityId">): string;
export declare function selectDynamicFusionBudget(ranked: readonly GeneralizedFusionCandidate[], options?: {

@@ -44,0 +53,0 @@ maxCandidates?: number;

import type { FactMemory, UserProfile } from "../domain/records";
import type { LanguageService } from "../language";
import type { LanguageQueryAnalysis, LanguageService } from "../language";
import type { RecallCandidateTrace } from "./engine";

@@ -7,9 +7,9 @@ import type { RetrievalProfile, RoutingDecision } from "./router";

import type { GeneralizedFusionSelectionInput } from "./factSelection/generalizedFusionUnion";
export type FactSelector = (facts: FactMemory[], query: string, language: LanguageService, queryLocale: string, retrievalProfile: RetrievalProfile, routingDecision: RoutingDecision, profile: UserProfile | null, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>, semanticUnion?: SemanticUnionSelectionInput, generalizedFusion?: GeneralizedFusionSelectionInput) => {
export type FactSelector = (facts: FactMemory[], query: string, language: LanguageService, queryLocale: string, retrievalProfile: RetrievalProfile, routingDecision: RoutingDecision, profile: UserProfile | null, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>, semanticUnion?: SemanticUnionSelectionInput, generalizedFusion?: GeneralizedFusionSelectionInput, queryAnalysis?: LanguageQueryAnalysis) => {
facts: FactMemory[];
traces: RecallCandidateTrace[];
};
export declare function selectGeneralizedFactsForInternalUse(facts: FactMemory[], query: string, language: LanguageService, queryLocale: string, _retrievalProfile: RetrievalProfile, routingDecision: RoutingDecision, profile: UserProfile | null, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>, semanticUnion?: SemanticUnionSelectionInput, generalizedFusion?: GeneralizedFusionSelectionInput): {
export declare function selectGeneralizedFactsForInternalUse(facts: FactMemory[], query: string, language: LanguageService, queryLocale: string, _retrievalProfile: RetrievalProfile, routingDecision: RoutingDecision, profile: UserProfile | null, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>, semanticUnion?: SemanticUnionSelectionInput, generalizedFusion?: GeneralizedFusionSelectionInput, providedQueryAnalysis?: LanguageQueryAnalysis): {
facts: FactMemory[];
traces: RecallCandidateTrace[];
};

@@ -0,2 +1,7 @@

export interface BridgeTextAnalysis {
entities: readonly string[];
tokens: readonly string[];
}
export declare function extractBridgeEntities(input: {
analyzeBridgeText: (text: string) => BridgeTextAnalysis;
facts: readonly {

@@ -9,2 +14,3 @@ content: string;

export interface IterativeRecallOptions {
analyzeBridgeText?: (text: string) => BridgeTextAnalysis;
bridgeEntityLimit?: number;

@@ -26,3 +32,12 @@ maxHops?: number;

result: TResult;
steps: IterativeRecallStep[];
stopReason: IterativeRecallStopReason;
}
export type IterativeRecallStopReason = "expander_stopped" | "max_hops_reached" | "no_bridge_entities" | "no_new_evidence" | "unchanged_query";
export interface IterativeRecallStep {
bridgeEntities: string[];
factCount: number;
hop: number;
query: string;
}
export declare function iterativeRecall<TResult extends {

@@ -29,0 +44,0 @@ facts: readonly {

@@ -1,10 +0,13 @@

import type { DocumentStore } from "../../storage/contracts";
import type { ProjectionCapableDocumentStore } from "../../storage/contracts";
import type { RecallProjectionSearchPort } from "./contracts";
import type { KeyedMutationLock } from "./mutationLock";
import type { ProjectionManifestTracker } from "./manifest";
import type { RecallProjectionOperations } from "./operations";
import type { RecallProjectionRepairs } from "./repairs";
import { type ProjectionValidationFence } from "./validationFence";
export type EnsureScopeIndexed = RecallProjectionSearchPort["ensureScopeIndexed"];
export declare function createEnsureScopeIndexed(input: {
analyzerFingerprint: string | null;
bulkBackfill?: boolean;
documentStore: DocumentStore;
documentStore: ProjectionCapableDocumentStore;
mutationLock: KeyedMutationLock;

@@ -14,2 +17,4 @@ now: () => string;

repairs: RecallProjectionRepairs;
manifests: ProjectionManifestTracker;
validationFence: ProjectionValidationFence;
}): EnsureScopeIndexed;
import type { MemoryScope } from "../../domain/scope";
import type { MemorySourceMethod } from "../../domain/provenance";
export declare const RECALL_DOCUMENTS_COLLECTION = "recall_documents_v2";
export declare const ENTITIES_COLLECTION = "entities_v1";
export declare const SCOPE_CATALOG_COLLECTION = "scope_catalog_v1";
import type { AppendClaimProjectionInput, MemoryClaimModality, MemoryClaimPolarity } from "../../domain/memoryCandidate";
export type { AppendClaimProjectionInput, ClaimProjectionWritePort, } from "../../domain/memoryCandidate";
export declare const RECALL_DOCUMENTS_COLLECTION = "recall_documents_v3";
export declare const ENTITIES_COLLECTION = "entities_v2";
export declare const SCOPE_CATALOG_COLLECTION = "scope_catalog_v2";
export declare const PROJECTION_MANIFESTS_COLLECTION = "recall_projection_manifests_v1";
export declare const PROJECTION_REPAIRS_COLLECTION = "recall_projection_repairs_v1";
export declare const CLAIM_PROJECTIONS_COLLECTION = "claim_projections_v2";
export declare const CLAIM_PROJECTION_STATUS_COLLECTION = "claim_projection_status_v2";
export declare const PROJECTION_SEARCH_SCHEMA_VERSION = "gm-search-v2";
export declare const RECALL_PROJECTION_PIPELINE_VERSION = "gm-projection-v3";
export declare const LEGACY_RECALL_PROJECTION_COLLECTIONS: readonly ["recall_documents_v2", "entities_v1", "claim_projections_v1", "claim_projection_status_v1", "scope_catalog_v1"];
export declare const RECALL_PROJECTION_SOURCE_COLLECTIONS: readonly ["profiles", "preferences", "references", "facts", "episodes", "feedback", "session_archives"];

@@ -17,3 +25,3 @@ export type RecallProjectionSourceCollection = (typeof RECALL_PROJECTION_SOURCE_COLLECTIONS)[number];

id: string;
schemaVersion: 2;
schemaVersion: 3;
scopeKey: string;

@@ -26,2 +34,7 @@ sourceCollection: RecallProjectionSourceCollection;

text: string;
searchText: string;
searchLocale: string;
languagePackId: string;
searchAnalyzerVersion: string;
searchSchemaVersion: typeof PROJECTION_SEARCH_SCHEMA_VERSION;
entityIds: string[];

@@ -36,2 +49,5 @@ entityMentions: RecallEntityMention[];

locale?: string;
localeSource?: "explicit" | "detected" | "default";
languagePackId?: string;
languagePackVersion?: string;
};

@@ -44,3 +60,3 @@ sourceCreatedAt?: string;

id: string;
schemaVersion: 1;
schemaVersion: 2;
scopeKey: string;

@@ -57,3 +73,3 @@ canonicalKey: string;

id: string;
schemaVersion: 1;
schemaVersion: 2;
scopeKey: string;

@@ -65,2 +81,8 @@ entityId: string;

description?: string;
text: string;
searchText: string;
searchLocale: string;
languagePackId: string;
searchAnalyzerVersion: string;
searchSchemaVersion: typeof PROJECTION_SEARCH_SCHEMA_VERSION;
validFrom?: string;

@@ -72,8 +94,63 @@ validUntil?: string;

id: string;
schemaVersion: 1;
schemaVersion: 2;
scopeKey: string;
coverage: "partial" | "complete";
analyzerFingerprint: string | null;
projectionVersion: typeof RECALL_PROJECTION_PIPELINE_VERSION;
searchSchemaVersion: typeof PROJECTION_SEARCH_SCHEMA_VERSION;
firstSeenAt: string;
lastSeenAt: string;
}
export interface RecallProjectionManifest extends MemoryScope {
id: string;
schemaVersion: 1;
scopeKey: string;
sourceGeneration: string;
validatedGeneration?: string;
projectionBuildId?: string;
updatedAt: string;
validatedAt?: string;
}
export interface ClaimProjection extends MemoryScope {
id: string;
schemaVersion: 2;
scopeKey: string;
sourceMemoryId: string;
subjectText?: string;
subjectEntityId: string;
predicateKey: string;
objectText: string;
text: string;
searchText: string;
searchLocale: string;
languagePackId: string;
searchAnalyzerVersion: string;
searchSchemaVersion: typeof PROJECTION_SEARCH_SCHEMA_VERSION;
objectEntityText?: string;
objectEntityId?: string;
polarity: MemoryClaimPolarity;
modality: MemoryClaimModality;
validFrom?: string;
validUntil?: string;
observedAt: string;
ingestedAt: string;
evidenceIds: string[];
sourceMessageIds: string[];
extractorVersion: string;
confidence?: number;
contextualDescriptor?: string;
}
export type ClaimProjectionState = "projected" | "unstructured" | "failed";
export interface ClaimProjectionStatus extends MemoryScope {
id: string;
schemaVersion: 2;
scopeKey: string;
sourceMemoryId: string;
state: ClaimProjectionState;
claimIds: string[];
extractorVersion: string;
sourceUpdatedAt?: string;
lastError?: string;
updatedAt: string;
}
export interface ProjectionRepairRecord extends MemoryScope {

@@ -89,2 +166,4 @@ id: string;

lastError: string;
target?: "recall" | "claim";
claimInput?: AppendClaimProjectionInput;
}

@@ -98,4 +177,11 @@ export interface RecallProjectionSearchPort {

queryDocuments(scope: MemoryScope): Promise<RecallIndexDocument[]>;
searchDocuments(scope: MemoryScope, query: string, limit: number, locale?: string): Promise<RecallIndexDocument[]>;
searchEntities(scope: MemoryScope, query: string, limit: number, locale?: string): Promise<EntityProjection[]>;
searchClaims(scope: MemoryScope, query: string, limit: number, history?: boolean, locale?: string): Promise<ClaimProjection[]>;
queryEntities(scope: MemoryScope): Promise<EntityProjection[]>;
queryClaims(scope: MemoryScope): Promise<ClaimProjection[]>;
queryClaimsBySourceMemoryIds(scope: MemoryScope, sourceMemoryIds: readonly string[]): Promise<ClaimProjection[]>;
queryClaimsForSourceMemoryGroups(scope: MemoryScope, sourceMemoryIds: readonly string[]): Promise<ClaimProjection[]>;
queryClaimHistory(scope: MemoryScope): Promise<ClaimProjection[]>;
}
export declare function isRecallProjectionSourceCollection(collection: string): collection is RecallProjectionSourceCollection;
import type { MemoryScope } from "../../domain/scope";
import type { DocumentStore } from "../../storage/contracts";
import type { LanguageService } from "../../language";
import type { EntityAdjacencyProjection, EntityProjection, RecallIndexDocument, RecallProjectionSourceCollection } from "./contracts";
export interface EntityProjectionIndex {
query(scope: MemoryScope): Promise<EntityProjection[]>;
search(scope: MemoryScope, query: string, limit: number, locale?: string): Promise<EntityProjection[]>;
updateForSource(input: {

@@ -16,6 +18,12 @@ collection: RecallProjectionSourceCollection;

}
export declare function buildEntityProjectionSearchText(input: {
aliases: readonly string[];
canonicalKey: string;
description?: string;
}): string;
export declare function buildEntityAdjacencyProjections(input: {
documents: readonly RecallIndexDocument[];
language: LanguageService;
timestamp: string;
}): EntityAdjacencyProjection[];
export declare function createEntityProjectionIndex(documentStore: DocumentStore): EntityProjectionIndex;
export declare function createEntityProjectionIndex(documentStore: DocumentStore, language: LanguageService): EntityProjectionIndex;
import type { MemoryScope } from "../../domain/scope";
import type { DocumentStore, StorageDocument } from "../../storage/contracts";
import type { EntityProjection, RecallIndexDocument, RecallProjectionSourceCollection, ScopeCatalogProjection } from "./contracts";
import type { EvidenceRecord } from "../../evidence/contracts";
import type { LanguageService } from "../../language";
import type { ProjectionCapableDocumentStore, StorageDocument } from "../../storage/contracts";
import type { ClaimProjectionIndex } from "./claims";
import type { AppendClaimProjectionInput, ClaimProjection, EntityProjection, RecallIndexDocument, RecallProjectionSourceCollection, ScopeCatalogProjection } from "./contracts";
import type { EntityProjectionIndex } from "./entityIndex";
export interface RecallProjectionOperations {
appendClaimUnsafe(input: AppendClaimProjectionInput): Promise<void>;
markClaimFailed(input: AppendClaimProjectionInput, error: unknown): Promise<void>;
queryClaims(scope: MemoryScope): Promise<ClaimProjection[]>;
queryClaimsBySourceMemoryIds(scope: MemoryScope, sourceMemoryIds: readonly string[]): Promise<ClaimProjection[]>;
queryClaimsForSourceMemoryGroups(scope: MemoryScope, sourceMemoryIds: readonly string[]): Promise<ClaimProjection[]>;
queryClaimHistory(scope: MemoryScope): Promise<ClaimProjection[]>;
queryDocuments(scope: MemoryScope): Promise<RecallIndexDocument[]>;
searchDocuments(scope: MemoryScope, query: string, limit: number, locale?: string): Promise<RecallIndexDocument[]>;
searchEntities(scope: MemoryScope, query: string, limit: number, locale?: string): Promise<EntityProjection[]>;
searchClaims(scope: MemoryScope, query: string, limit: number, history?: boolean, locale?: string): Promise<ClaimProjection[]>;
queryEntities(scope: MemoryScope): Promise<EntityProjection[]>;
registerScope(scope: MemoryScope, timestamp: string, coverage?: ScopeCatalogProjection["coverage"]): Promise<void>;
rebuildScopeUnsafe(scope: MemoryScope, sources: readonly RecallProjectionCanonicalSource[]): Promise<number>;
synchronizeUnsafe(collection: RecallProjectionSourceCollection, sourceMemoryId: string, fallbackScope?: MemoryScope, recoverStaleAdjacency?: boolean): Promise<void>;
reconcileClaimScopeUnsafe(scope: MemoryScope, sources: readonly RecallProjectionCanonicalSource[]): Promise<void>;
synchronizeUnsafe(collection: RecallProjectionSourceCollection, sourceMemoryId: string, fallbackScope?: MemoryScope, recoverStaleAdjacency?: boolean, evidence?: readonly EvidenceRecord[]): Promise<void>;
validateScopeUnsafe(scope: MemoryScope, sources: readonly RecallProjectionCanonicalSource[], evidenceIds: ReadonlySet<string>): Promise<{
complete: boolean;
issues: string[];
}>;
}

@@ -15,8 +32,12 @@ export interface RecallProjectionCanonicalSource {

document: StorageDocument;
evidence?: readonly EvidenceRecord[];
id: string;
}
export declare function createRecallProjectionOperations(input: {
documentStore: DocumentStore;
analyzerFingerprint: string | null;
documentStore: ProjectionCapableDocumentStore;
language: LanguageService;
now: () => string;
entityIndex?: EntityProjectionIndex;
claimIndex?: ClaimProjectionIndex;
}): RecallProjectionOperations;

@@ -0,6 +1,9 @@

import type { MemorySource } from "../../domain/provenance";
import type { MemoryScope } from "../../domain/scope";
import type { StorageDocument } from "../../storage/contracts";
import type { LanguageService, ResolvedLanguageContext } from "../../language";
import type { RecallIndexDocument, RecallProjectionSourceCollection } from "./contracts";
export declare function buildEntityProjectionId(scopeKey: string, canonicalKey: string): string;
export declare function buildEntityAdjacencyProjectionId(entityId: string, memoryId: string): string;
export declare function resolveProjectionLanguageContext(language: LanguageService, text: string, source?: Partial<MemorySource>): ResolvedLanguageContext;
export declare function resolveProjectionScope(document: StorageDocument): MemoryScope | null;

@@ -11,3 +14,4 @@ export declare function buildRecallIndexDocuments(input: {

indexedAt: string;
language: LanguageService;
sourceMemoryId: string;
}): RecallIndexDocument[];
import type { MemoryScope } from "../../domain/scope";
import type { DocumentStore } from "../../storage/contracts";
import type { RecallProjectionSourceCollection } from "./contracts";
import type { ProjectionCapableDocumentStore, StorageDocument } from "../../storage/contracts";
import type { AppendClaimProjectionInput, RecallProjectionSourceCollection } from "./contracts";
import type { KeyedMutationLock } from "./mutationLock";
import type { ProjectionManifestMutation } from "./manifest";
import type { RecallProjectionOperations } from "./operations";

@@ -12,4 +13,8 @@ export interface ProjectionRepairInput {

sourceMemoryId: string;
target?: "recall" | "claim";
claimInput?: AppendClaimProjectionInput;
}
export interface RecallProjectionRepairs {
deleteCanonicalAndRepairs(collection: RecallProjectionSourceCollection, sourceMemoryId: string, canonical: StorageDocument, manifestMutation?: ProjectionManifestMutation): Promise<boolean>;
discardSource(collection: RecallProjectionSourceCollection, sourceMemoryId: string): Promise<void>;
queue(input: ProjectionRepairInput): Promise<void>;

@@ -19,3 +24,3 @@ repairPending(scope: MemoryScope): Promise<number>;

export declare function createRecallProjectionRepairs(input: {
documentStore: DocumentStore;
documentStore: ProjectionCapableDocumentStore;
mutationLock: KeyedMutationLock;

@@ -22,0 +27,0 @@ now: () => string;

import type { MemoryScope } from "../../domain/scope";
import type { DocumentStore } from "../../storage/contracts";
import type { RecallProjectionSearchPort } from "./contracts";
export interface RecallProjectionRuntime extends RecallProjectionSearchPort {
documentStore: DocumentStore;
import { type LanguageService } from "../../language";
import { type ScopeDeletionCoordinator } from "../../storage/scopeDeletion";
import { type DocumentStore, type ProjectionCapableDocumentStore } from "../../storage/contracts";
import type { ClaimProjectionWritePort, RecallProjectionSearchPort } from "./contracts";
export interface RecallProjectionRuntime extends ClaimProjectionWritePort, RecallProjectionSearchPort {
documentStore: ProjectionCapableDocumentStore;
repairPending(scope: MemoryScope): Promise<number>;
scopeDeletion: ScopeDeletionCoordinator;
}

@@ -11,5 +14,9 @@ export interface RecallProjectionRuntimeConfig {

documentStore: DocumentStore;
language?: LanguageService;
now?: () => string;
persistentScopeProof?: {
buildId: string;
};
writeThrough?: boolean;
}
export declare function createRecallProjectionRuntime(config: RecallProjectionRuntimeConfig): RecallProjectionRuntime;

@@ -1,7 +0,8 @@

import type { DocumentStore } from "../../storage/contracts";
import type { ProjectionCapableDocumentStore } from "../../storage/contracts";
import type { KeyedMutationLock } from "./mutationLock";
import type { RecallProjectionOperations } from "./operations";
import type { RecallProjectionRepairs } from "./repairs";
import type { ProjectionManifestTracker } from "./manifest";
export declare function createProjectionAwareDocumentStore(input: {
documentStore: DocumentStore;
documentStore: ProjectionCapableDocumentStore;
mutationLock: KeyedMutationLock;

@@ -11,3 +12,4 @@ now: () => string;

repairs: RecallProjectionRepairs;
manifests: ProjectionManifestTracker;
writeThrough: boolean;
}): DocumentStore;
}): ProjectionCapableDocumentStore;

@@ -0,2 +1,6 @@

import { type LanguageService } from "../language";
export interface QueryDecompositionOptions {
/** Locale-aware tokenizer/sentence splitter used by the recall planner. */
language?: Pick<LanguageService, "decomposeQuery" | "normalizeForEquality" | "resolveFromText" | "tokenize">;
locale?: string;
/** Maximum number of sub-queries to keep (excludes the original query). Default 4. */

@@ -3,0 +7,0 @@ maxSubQueries?: number;

@@ -1,2 +0,4 @@

export type RecallRetrievalChannel = "dense" | "entity" | "lexical";
import type { IterativeRecallStep, IterativeRecallStopReason } from "./iterativeRecall";
import type { RecallPlan } from "./recallPlan";
export type RecallRetrievalChannel = "dense" | "entity" | "lexical" | "relation" | "temporal";
export type RecallRetrievalSourceCollection = "episodes" | "facts" | "feedback" | "preferences" | "profiles" | "references" | "session_archives";

@@ -11,2 +13,3 @@ export interface RecallRetrievalChannelTrace {

channels: Partial<Record<RecallRetrievalChannel, RecallRetrievalChannelTrace>>;
eliminationReason?: "not_selected";
evidenceTypes: RecallRetrievalChannel[];

@@ -23,4 +26,8 @@ evidenceStrength: number;

candidates: RecallFusionCandidateTrace[];
fallbackReason?: "projection_error" | "projection_unavailable";
fallbackReason?: "projection_error" | "projection_incomplete" | "projection_unavailable";
projectionCoverage?: "complete" | "partial";
hop?: number;
query?: string;
queryRole?: "primary" | "subquery";
subQueryIndex?: number;
status: "applied" | "fallback";

@@ -34,2 +41,3 @@ }

score: number;
sourceCollection?: RecallRetrievalSourceCollection;
}

@@ -50,6 +58,26 @@ export interface RecallRerankerTrace {

}
export interface RecallRetrievalTrace {
interface RecallRetrievalTraceBase {
fusionRuns?: RecallFusionRunTrace[];
reranker?: RecallRerankerTrace;
}
export interface RecallRetrievalTraceV1 extends RecallRetrievalTraceBase {
schemaVersion: 1;
}
export interface RecallQueryExecutionTrace {
hops: IterativeRecallStep[];
plan?: RecallPlan;
query: string;
role: "primary" | "subquery";
stopReason: IterativeRecallStopReason | "single_pass_complete";
subQueryIndex?: number;
}
export type RecallExecutionStopReason = "decomposition_complete" | "multi_hop_complete" | "single_pass_complete";
export interface RecallRetrievalTraceV2 extends RecallRetrievalTraceBase {
plan: RecallPlan;
queryExecutions: RecallQueryExecutionTrace[];
schemaVersion: 2;
stopReason: RecallExecutionStopReason;
subQueries: string[];
}
export type RecallRetrievalTrace = RecallRetrievalTraceV1 | RecallRetrievalTraceV2;
export {};

@@ -1,2 +0,2 @@

import { type LanguageService } from "../language";
import type { LanguageQueryAnalysis, LanguageService } from "../language";
export type RetrievalProfile = "general_chat" | "coding_agent";

@@ -46,2 +46,3 @@ export type RecallRouterStrategy = "rules-only" | "hybrid" | "llm-assisted" | "auto";

language?: LanguageService;
queryAnalysis?: LanguageQueryAnalysis;
}

@@ -48,0 +49,0 @@ interface AutoRouterSignals {

@@ -6,3 +6,3 @@ import type { EpisodeMemory, FactKind, FactMemory, FeedbackMemory, MemoryScopeKind, PreferenceMemory, ReferenceKind, ReferenceMemory } from "../domain/records";

import type { SessionArchive } from "../domain/evolutionRecords";
import type { LanguageService } from "../language";
import type { LanguageQueryAnalysis, LanguageService } from "../language";
import type { RecallVectorSearchPort } from "../storage/ports";

@@ -84,3 +84,3 @@ import type { RecallRouterStrategy } from "./router";

export declare function explicitnessScore(method: MemorySourceMethod): number;
export declare function buildFactCandidates(facts: FactMemory[], query: string, language: LanguageService, queryLocale: string, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>): RankedFactCandidate[];
export declare function buildFactCandidates(facts: FactMemory[], query: string, language: LanguageService, queryLocale: string, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>, providedQueryAnalysis?: LanguageQueryAnalysis): RankedFactCandidate[];
export declare function buildReferenceCandidates(references: ReferenceMemory[], query: string, language: LanguageService, queryLocale: string, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>): RankedReferenceCandidate[];

@@ -87,0 +87,0 @@ export declare function buildEpisodeCandidates(episodes: EpisodeMemory[], query: string, language: LanguageService, queryLocale: string, referenceTime: string, semanticScores?: Map<string, number>): RankedEpisodeCandidate[];

@@ -1,9 +0,3 @@

import type { FactSelector } from "./generalizedSelection";
import { selectGeneralizedFactsForInternalUse } from "./generalizedSelection";
export { selectGeneralizedFactsForInternalUse, };
export type { FactSelector };
export { selectGeneralizedFactsForInternalUse as selectFacts, selectGeneralizedFactsForInternalUse, } from "./generalizedSelection";
export type { FactSelector } from "./generalizedSelection";
export { selectArchives, selectEpisodes, selectFeedback, selectFeedbackForProfile, selectFeedbackForQuery, selectPreferencesForQuery, selectReferences, } from "./selectors/recordSelection";
export declare const selectFacts: FactSelector;
/** Repo-only compatibility seam for historical evals and focused legacy tests. */
export declare function setFactSelectorForInternalEval(selector: FactSelector | undefined): void;
export declare function __resetFactSelectorForTest(): void;
import type { EpisodeMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory } from "../../domain/records";
import type { SessionArchive } from "../../domain/evolutionRecords";
import type { LanguageService } from "../../language";
import type { LanguageQueryAnalysis, LanguageService } from "../../language";
import type { RecallCandidateTrace } from "../engine";

@@ -8,5 +8,5 @@ import type { RetrievalProfile, RoutingDecision } from "../router";

export declare function selectFeedbackForProfile(feedback: FeedbackMemory[], retrievalProfile: RetrievalProfile): FeedbackMemory[];
export declare function selectFeedbackForQuery(feedback: FeedbackMemory[], query: string, language: LanguageService, queryLocale: string, retrievalProfile: RetrievalProfile): FeedbackMemory[];
export declare function selectPreferencesForQuery(preferences: PreferenceMemory[], query: string, language: LanguageService, queryLocale: string): PreferenceMemory[];
export declare function selectReferences(references: ReferenceMemory[], query: string, language: LanguageService, queryLocale: string, routingDecision: RoutingDecision, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>): {
export declare function selectFeedbackForQuery(feedback: FeedbackMemory[], query: string, language: LanguageService, queryLocale: string, retrievalProfile: RetrievalProfile, providedQueryAnalysis?: LanguageQueryAnalysis): FeedbackMemory[];
export declare function selectPreferencesForQuery(preferences: PreferenceMemory[], query: string, language: LanguageService, queryLocale: string, providedQueryAnalysis?: LanguageQueryAnalysis): PreferenceMemory[];
export declare function selectReferences(references: ReferenceMemory[], query: string, language: LanguageService, queryLocale: string, routingDecision: RoutingDecision, referenceTime: string, semanticScores?: Map<string, number>, evidenceCountsByMemoryId?: Map<string, number>, providedQueryAnalysis?: LanguageQueryAnalysis): {
references: ReferenceMemory[];

@@ -13,0 +13,0 @@ traces: RecallCandidateTrace[];

@@ -7,34 +7,9 @@ import type { FeedbackMemory, PreferenceMemory } from "../../domain/records";

export declare const PROJECT_STATE_SUPPORT_FALLBACK_KINDS: readonly ["focus_update", "project_state"];
export declare const ASSISTANT_EVIDENCE_RECALL_LIMIT = 6;
export declare const DIRECT_FACTUAL_RECALL_LIMIT = 6;
export declare const DIRECT_FACTUAL_COMPANION_LIMIT = 3;
export declare const PREFERENCE_EVIDENCE_RECALL_LIMIT = 4;
export declare const TEMPORAL_BRIDGE_EVIDENCE_RECALL_LIMIT = 4;
export declare const UPDATE_EVIDENCE_RECALL_LIMIT = 3;
export declare const PREFERENCE_RECALL_LIMIT = 3;
export declare const RESEARCH_RECOMMENDATION_LIMIT = 2;
export declare const EXPLICIT_WEAK_LEXICAL_FACT_THRESHOLD = 0.08;
export declare const AGGREGATE_TRUSTED_EVIDENCE_TAGS: Set<string>;
export declare const ASSISTANT_EVIDENCE_TAG = "assistant_answer";
export declare const SOURCE_MESSAGE_TAG = "source_message";
export declare const SOURCE_ORDER_TAG = "source_order";
export declare const CONVERSATION_EVIDENCE_TAGS: Set<string>;
export declare const DIRECT_FACTUAL_COMPANION_TAGS: Set<string>;
export declare const QUANTIFIED_FACT_PATTERN: RegExp;
export declare const PERSONAL_ELECTRONICS_FACT_PATTERN: RegExp;
export declare const INSTRUMENT_PRACTICE_FACT_PATTERN: RegExp;
export declare const ENTITY_BEARING_FACT_PATTERN: RegExp;
export declare const ASSISTANT_COUNT_HEADING_FACT_PATTERN: RegExp;
export declare function hasConversationEvidenceTag(entry: RankedFactCandidate): boolean;
export declare function hasAssistantAnswerTag(entry: RankedFactCandidate): boolean;
export declare function hasSourceMessageTag(entry: RankedFactCandidate): boolean;
export declare function hasDirectFactualCompanionTag(entry: RankedFactCandidate): boolean;
export declare function hasUserAnswerTag(entry: RankedFactCandidate): boolean;
export declare function isDatedEventFact(entry: RankedFactCandidate): boolean;
export declare function hasTrustedAggregateEvidence(entry: RankedFactCandidate): boolean;
export declare function isAssistantProvidedDetailRecallQuery(query: string): boolean;
export declare function explicitlyAsksForAssistantProvidedDetail(query: string): boolean;
export declare function isUserGroundedRecallQuery(query: string): boolean;
export declare function stripEvidencePrefix(content: string): string;
export declare function isInstrumentPracticeTimeQuery(query: string): boolean;
export declare function diversifyRankedFactCandidatesBySession(entries: RankedFactCandidate[], limit: number): RankedFactCandidate[];

@@ -48,4 +23,2 @@ export declare function preferenceSearchText(preference: PreferenceMemory): string;

export declare function hasGenericFactSelectionSignal(entry: RankedFactCandidate): boolean;
export declare function valueBearingFactContent(content: string): string;
export declare function hasEntityBearingEvidenceSignal(entry: RankedFactCandidate): boolean;
export declare function feedbackApplicabilityPriority(feedback: FeedbackMemory, retrievalProfile: RetrievalProfile): number;

@@ -1,15 +0,27 @@

import type { FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, UserProfile } from "../domain/records";
import type { EvidenceRecord } from "../evidence/contracts";
import type { FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionMessage, UserProfile } from "../domain/records";
import type { EvidenceRecord, SourceMessageRecord } from "../evidence/contracts";
import type { ClassifiedCandidate, ScopedIdentity } from "./contracts";
export interface SourceLanguageMetadata {
locale: string;
localeSource?: "explicit" | "detected" | "default";
languagePackId?: string;
languagePackVersion?: string;
}
export declare function buildProfile(userId: string, existing: UserProfile | null, candidate: ClassifiedCandidate, timestamp: string): UserProfile;
export declare function getProfileWriteReason(candidate: ClassifiedCandidate): string;
export declare function buildPreference(scope: ScopedIdentity, candidate: ClassifiedCandidate, id: string, timestamp: string, locale: string): PreferenceMemory;
export declare function buildReference(scope: ScopedIdentity, candidate: ClassifiedCandidate, id: string, timestamp: string, locale: string): ReferenceMemory;
export declare function buildPreference(scope: ScopedIdentity, candidate: ClassifiedCandidate, id: string, timestamp: string, language: SourceLanguageMetadata | string): PreferenceMemory;
export declare function buildReference(scope: ScopedIdentity, candidate: ClassifiedCandidate, id: string, timestamp: string, language: SourceLanguageMetadata | string): ReferenceMemory;
export declare function resolveReferenceSubject(candidate: ClassifiedCandidate, scopedReferences: ReferenceMemory[]): string;
export declare function buildFact(scope: ScopedIdentity, candidate: ClassifiedCandidate, id: string, timestamp: string, locale: string): FactMemory;
export declare function enrichDuplicatePreference(preference: PreferenceMemory, candidate: ClassifiedCandidate, timestamp: string, locale: string): PreferenceMemory | null;
export declare function enrichDuplicateFact(fact: FactMemory, candidate: ClassifiedCandidate, timestamp: string, locale: string): FactMemory | null;
export declare function enrichDuplicateReference(reference: ReferenceMemory, candidate: ClassifiedCandidate, timestamp: string, locale: string): ReferenceMemory | null;
export declare function buildFeedback(scope: ScopedIdentity, candidate: ClassifiedCandidate, id: string, timestamp: string, locale: string): FeedbackMemory;
export declare function enrichDuplicateFeedback(feedback: FeedbackMemory, candidate: ClassifiedCandidate, timestamp: string, locale: string): FeedbackMemory | null;
export declare function buildCandidateEvidence(scope: ScopedIdentity, candidate: ClassifiedCandidate, memoryId: string, evidenceId: string, timestamp: string, locale: string, sourceMessageContent?: string): EvidenceRecord;
export declare function resolveCandidateObservedAt(candidate: ClassifiedCandidate, messages: readonly {
observedAt?: string;
}[]): string | undefined;
export declare function buildFact(scope: ScopedIdentity, candidate: ClassifiedCandidate, id: string, timestamp: string, language: SourceLanguageMetadata | string, observedAt?: string): FactMemory;
export declare function enrichDuplicatePreference(preference: PreferenceMemory, candidate: ClassifiedCandidate, timestamp: string, language: SourceLanguageMetadata | string): PreferenceMemory | null;
export declare function enrichDuplicateFact(fact: FactMemory, candidate: ClassifiedCandidate, timestamp: string, language: SourceLanguageMetadata | string): FactMemory | null;
export declare function enrichDuplicateReference(reference: ReferenceMemory, candidate: ClassifiedCandidate, timestamp: string, language: SourceLanguageMetadata | string): ReferenceMemory | null;
export declare function buildFeedback(scope: ScopedIdentity, candidate: ClassifiedCandidate, id: string, timestamp: string, language: SourceLanguageMetadata | string): FeedbackMemory;
export declare function enrichDuplicateFeedback(feedback: FeedbackMemory, candidate: ClassifiedCandidate, timestamp: string, language: SourceLanguageMetadata | string): FeedbackMemory | null;
export declare function buildSourceMessageRecords(scope: ScopedIdentity, candidate: ClassifiedCandidate, messages: readonly SessionMessage[], ingestedAt: string): SourceMessageRecord[];
export declare function buildSourceMessageRecord(scope: ScopedIdentity, message: SessionMessage, messageIndex: number, ingestedAt: string): SourceMessageRecord;
export declare function sourceMessageRecordUri(record: SourceMessageRecord): string;
export declare function buildCandidateEvidence(scope: ScopedIdentity, candidate: ClassifiedCandidate, memoryId: string, evidenceId: string, timestamp: string, language: SourceLanguageMetadata | string, sourceMessages?: readonly SourceMessageRecord[]): EvidenceRecord;

@@ -0,4 +1,5 @@

import type { SessionMessage } from "../domain/records";
import type { MemoryScope } from "../domain/scope";
import type { MemoryCandidate, MemoryCandidateAnnotationTrace, MemoryCandidateExplicitness, MemoryCandidateKindHint, MemoryCandidateMetadata, MemoryExtractionStrategy, MessageAnnotationRememberMode, ProfileField } from "../domain/memoryCandidate";
export type { MemoryCandidate, MemoryCandidateAnnotationTrace, MemoryCandidateExplicitness, MemoryCandidateKindHint, MemoryCandidateMetadata, MemoryExtractionStrategy, MessageAnnotationRememberMode, ProfileField, };
import type { AppendClaimProjectionInput, ClaimProjectionWritePort, MemoryCandidateClaimMetadata, MemoryCandidate, MemoryCandidateAnnotationTrace, MemoryCandidateExplicitness, MemoryCandidateKindHint, MemoryCandidateMetadata, MemoryClaimModality, MemoryClaimPolarity, MemoryExtractionStrategy, MessageAnnotationRememberMode, ProfileField } from "../domain/memoryCandidate";
export type { AppendClaimProjectionInput, ClaimProjectionWritePort, MemoryCandidateClaimMetadata, MemoryCandidate, MemoryCandidateAnnotationTrace, MemoryCandidateExplicitness, MemoryCandidateKindHint, MemoryCandidateMetadata, MemoryClaimModality, MemoryClaimPolarity, MemoryExtractionStrategy, MessageAnnotationRememberMode, ProfileField, };
export interface MessageAnnotation {

@@ -15,6 +16,3 @@ messageIndex: number;

scope: MemoryScope;
messages: Array<{
role: string;
content: string;
}>;
messages: SessionMessage[];
annotations?: MessageAnnotation[];

@@ -21,0 +19,0 @@ extractionStrategy?: MemoryExtractionStrategy;

@@ -0,3 +1,5 @@

import type { MemorySourceMethod } from "../domain/provenance";
import type { EmbeddingAdapter } from "../embedding/contracts";
import type { MemoryEmbeddingWrite, PreparedMemoryEmbeddingRecord } from "../embedding/vectorWrites";
import type { SourceMessageRecord } from "../evidence/contracts";
import type { LanguageService, ResolvedLanguageContext } from "../language";

@@ -7,5 +9,4 @@ import type { GoodMemoryPolicyHooks, PolicyContext } from "../policy/hooks";

import type { RememberRepositoryPort, RememberVectorPort } from "../storage/ports";
import type { MemoryCandidate, MemoryCandidateAnnotationTrace, MemoryCandidateKindHint, MemoryExtractionInput, MemoryExtractionStrategy, MemoryExtractor } from "./candidates";
import type { AppendClaimProjectionInput, ClaimProjectionWritePort, MemoryCandidate, MemoryCandidateAnnotationTrace, MemoryCandidateKindHint, MemoryExtractionInput, MemoryExtractionStrategy, MemoryExtractor } from "./candidates";
import type { RememberConfig } from "./profiles";
import type { MemorySourceMethod } from "../domain/provenance";
export type ScopedIdentity = {

@@ -39,2 +40,3 @@ userId: string;

}
export type ExtractionOutcome = "committed" | "no_admissible_candidate" | "failed";
export interface RememberResult {

@@ -44,2 +46,3 @@ accepted: number;

events: RememberEvent[];
outcome?: ExtractionOutcome;
warnings?: string[];

@@ -49,3 +52,4 @@ metadata?: {

localeSource: "explicit" | "detected" | "default";
adapterId: string;
languagePackId: string;
languagePackVersion?: string;
analysisMode: "rules-only";

@@ -58,2 +62,3 @@ requestedExtractionStrategy: MemoryExtractionStrategy;

assistedExtractor?: MemoryExtractor;
claimProjection?: ClaimProjectionWritePort;
documentStore: DocumentStore;

@@ -84,2 +89,3 @@ embedding?: EmbeddingAdapter;

pendingEmbeddingWrites: MemoryEmbeddingWrite[];
pendingClaimProjections: AppendClaimProjectionInput[];
pendingVectorDeletes: PendingVectorDelete[];

@@ -89,4 +95,5 @@ }

input: MemoryExtractionInput;
resolvedLanguage: ResolvedLanguageContext;
candidateLanguage: ResolvedLanguageContext;
language: LanguageService;
storedLanguageContexts: Map<string, ResolvedLanguageContext>;
policyContext: PolicyContext;

@@ -97,5 +104,6 @@ repositories: RememberRepositoryPort;

now: () => string;
policy?: Pick<GoodMemoryPolicyHooks, "resolveConflict">;
policy?: Pick<GoodMemoryPolicyHooks, "redact" | "resolveConflict">;
sourceMessagesByIndex: ReadonlyMap<number, SourceMessageRecord>;
setDocumentWithRollback: <TDocument extends object>(collection: string, id: string, document: TDocument) => Promise<void>;
deleteDocumentWithRollback: (collection: string, id: string) => Promise<void>;
}

@@ -1,5 +0,5 @@

import type { MemoryExtractor } from "./candidates";
import { type LanguageConfig, type LanguageService } from "../language";
export declare function createDeterministicMemoryExtractor(config?: (LanguageConfig & {
service?: LanguageService;
})): MemoryExtractor;
import type { LanguageConfig, LanguageService } from "../language";
import type { MemoryExtractionInput, MemoryExtractionResult, MemoryExtractor } from "./candidates";
import type { RememberSourceLanguageAnalyses } from "./languageAnalysis";
export declare function createDeterministicMemoryExtractor(config?: LanguageConfig): MemoryExtractor;
export declare function extractDeterministicMemoryWithLanguage(input: MemoryExtractionInput, language: LanguageService, providedAnalyses?: RememberSourceLanguageAnalyses): MemoryExtractionResult;
import { classifyCandidate } from "./classification";
import type { MemoryExtractionInput, MemoryExtractionResult } from "./candidates";
import type { RememberEngineConfig, RememberResult } from "./contracts";
import type { ExtractionOutcome, RememberEngineConfig, RememberResult } from "./contracts";
type EngineRememberResult = RememberResult & {
outcome: ExtractionOutcome;
};
export type { ClassifiedCandidate, RememberEngineConfig, RememberEvent, RememberResult, } from "./contracts";

@@ -8,3 +11,3 @@ export declare function createRememberEngine(config: RememberEngineConfig): {

extract(input: MemoryExtractionInput): Promise<MemoryExtractionResult>;
remember(input: MemoryExtractionInput): Promise<RememberResult>;
remember(input: MemoryExtractionInput): Promise<EngineRememberResult>;
};
import type { EpisodeMemory } from "../domain/records";
import type { LanguageService } from "../language";
import type { MemoryCandidate, MemoryExtractionInput } from "./candidates";
export declare function maybeBuildEpisode(input: MemoryExtractionInput, candidates: MemoryCandidate[], id: string, timestamp: string, language: LanguageService, locale: string): EpisodeMemory | null;
import type { RememberSourceLanguageAnalyses } from "./languageAnalysis";
export declare function maybeBuildEpisode(input: MemoryExtractionInput, candidates: MemoryCandidate[], id: string, timestamp: string, language: LanguageService, locale: string, sourceAnalyses?: RememberSourceLanguageAnalyses): EpisodeMemory | null;

@@ -0,3 +1,8 @@

import type { LanguageContentAnalysis, LanguageService, ResolvedLanguageContext } from "../language/contracts";
import type { MemoryCandidate } from "./candidates";
export declare function extractCanonicalReferencePointer(value: string | undefined): string | undefined;
export declare function normalizeMemoryCandidate(candidate: MemoryCandidate, sourceMessageContent?: string): MemoryCandidate;
export declare function normalizeMemoryCandidate(candidate: MemoryCandidate, sourceMessageContent?: string, languageContext?: {
analysis?: LanguageContentAnalysis;
language: LanguageService;
resolved: ResolvedLanguageContext;
}): MemoryCandidate;

@@ -0,1 +1,2 @@

import type { EvidenceLedgerFormat } from "../answer/evidenceLedgerContext";
import type { BuildContextResult, GoodMemory, RecallInput, RememberResult } from "../api/contracts";

@@ -120,2 +121,3 @@ import type { MemoryScope } from "../domain/scope";

defaultMaxMemoryTokens?: number;
evidenceLedgerFormat?: EvidenceLedgerFormat;
hostAdapter?: Pick<HostAdapter, "assessAction">;

@@ -122,0 +124,0 @@ memory: GoodMemory;

@@ -1,1 +0,1 @@

import{sa as t}from"../chunk-8f58rsqp.js";import"../chunk-jqpvhgjc.js";import"../chunk-cz5v71gv.js";import"../chunk-65h9nkw1.js";import"../chunk-jd15jhte.js";import"../chunk-m205c7rp.js";export{t as createGoodMemoryRuntimeKit};
import{oa as t}from"../chunk-njm7jqas.js";import"../chunk-963r53yf.js";import"../chunk-8d816xbx.js";import"../chunk-0h5pry7v.js";import"../chunk-jr0h5wkn.js";import"../chunk-c28647f0.js";import"../chunk-eqpe4gcb.js";export{t as createGoodMemoryRuntimeKit};
import type { SessionBuffer, SessionJournal, SessionMessage, WorkingMemorySnapshot } from "../domain/records";
import type { MemoryScope } from "../domain/scope";
import { type LanguageService } from "../language";
import type { ExtractionOutcome } from "../remember/contracts";
import type { ExtractionCursorStore } from "../remember/extractionCursor";
import type { SessionArchive } from "../domain/evolutionRecords";

@@ -24,5 +27,18 @@ import type { SessionStore } from "../storage/contracts";

}
export interface RuntimeExtractionInput {
from: number;
messages: SessionMessage[];
scope: MemoryScope;
sourceId: string;
through: number;
}
export interface RuntimeExtractionHooks {
cursorStore: ExtractionCursorStore;
extract(input: RuntimeExtractionInput): Promise<ExtractionOutcome>;
}
export interface RuntimeContextServiceConfig {
sessionStore: SessionStore;
archiveStore?: RuntimeArchiveStore;
extraction?: RuntimeExtractionHooks;
language?: LanguageService;
salvageHooks?: RuntimeSalvageHooks;

@@ -29,0 +45,0 @@ now?: () => string;

import type { SessionBuffer, SessionJournal, SessionMessage, WorkingMemorySnapshot } from "../domain/records";
import type { MemoryScope } from "../domain/scope";
import type { LanguageService } from "../language";
import type { DocumentStore, SessionStore } from "../storage/contracts";

@@ -12,2 +13,3 @@ import type { RuntimeArchiveStore, RuntimeContextState, RuntimeRecallSnapshot, SessionJournalPatch, SessionSummaryInput, WorkingMemoryPatch } from "./contextService";

archiveStore?: RuntimeArchiveStore;
language?: LanguageService;
now?: () => string;

@@ -14,0 +16,0 @@ createMessageId?: () => string;

@@ -5,2 +5,11 @@ import type { ArtifactSpillRecord } from "../domain/records";

export declare const ARTIFACT_SPILL_COLLECTION = "artifact_spills";
export declare const ARTIFACT_SPILL_PAYLOAD_COLLECTION = "artifact_spill_payloads_v1";
export interface ArtifactSpillPayloadRecord {
content: string;
contentHash: string;
createdAt: string;
id: string;
originalBytes: number;
scope: MemoryScope;
}
export interface SpillInput {

@@ -19,2 +28,3 @@ kind: ArtifactSpillRecord["kind"];

getBySource(scope: MemoryScope, sourceId: string): Promise<ArtifactSpillRecord | null>;
resolve(scope: MemoryScope, value: ArtifactSpillRecord | string): Promise<string | null>;
};
import type { SessionBuffer, SessionJournal, WorkingMemorySnapshot } from "../domain/records";
import type { MemoryScope } from "../domain/scope";
export type StorageDocument = object;
export type StorageFilter = Record<string, unknown>;
export type StorageFilter = Record<string, boolean | number | string | null>;
export declare const PROJECTION_BATCH_SEMANTICS: "unchanged-delete-v1";
export interface DocumentQueryPageInput {

@@ -14,2 +15,13 @@ cursor?: string;

}
export interface DocumentTextSearchInput {
field: string;
filter?: StorageFilter;
limit: number;
query: string;
}
export interface DocumentTextSearchResult<TDocument extends StorageDocument = StorageDocument> {
document: TDocument;
id: string;
score: number;
}
export interface DocumentWriteOperation<TDocument extends StorageDocument = StorageDocument> {

@@ -21,6 +33,20 @@ collection: string;

export interface ConditionalDocumentWriteBatch {
expected: DocumentWriteOperation;
delete?: Array<{
collection: string;
id: string;
}>;
expected: {
collection: string;
document: StorageDocument | null;
id: string;
};
set: DocumentWriteOperation[];
unchanged?: Array<{
collection: string;
document: StorageDocument | null;
id: string;
}>;
}
export interface DocumentStore {
projectionBatchSemantics?: string;
set<TDocument extends StorageDocument>(collection: string, id: string, document: TDocument): Promise<void>;

@@ -31,6 +57,15 @@ get<TDocument extends StorageDocument>(collection: string, id: string): Promise<TDocument | null>;

queryPage?<TDocument extends StorageDocument>(collection: string, input: DocumentQueryPageInput): Promise<DocumentQueryPage<TDocument>>;
searchText?<TDocument extends StorageDocument>(collection: string, input: DocumentTextSearchInput): Promise<DocumentTextSearchResult<TDocument>[]>;
writeBatchIfUnchanged?(input: ConditionalDocumentWriteBatch): Promise<boolean>;
delete(collection: string, id: string): Promise<void>;
}
export interface ProjectionCapableDocumentStore extends DocumentStore {
projectionBatchSemantics: typeof PROJECTION_BATCH_SEMANTICS;
scopeMutationFenceIdentity?: object;
writeBatchIfUnchanged(input: ConditionalDocumentWriteBatch): Promise<boolean>;
}
export declare function isProjectionCapableDocumentStore(store: DocumentStore): store is ProjectionCapableDocumentStore;
export declare function assertDocumentQueryPageInput(input: DocumentQueryPageInput): void;
export declare function assertDocumentTextSearchInput(input: DocumentTextSearchInput): void;
export declare function assertStorageFilter(filter?: StorageFilter): void;
export interface VectorRecord {

@@ -57,3 +92,5 @@ id: string;

saveBuffer(scope: MemoryScope, buffer: SessionBuffer): Promise<void>;
saveBufferIfUnchanged(scope: MemoryScope, expectedBuffer: SessionBuffer | null, nextBuffer: SessionBuffer): Promise<boolean>;
getBuffer(scope: MemoryScope): Promise<SessionBuffer | null>;
deleteBufferIfUnchanged(scope: MemoryScope, expectedBuffer: SessionBuffer): Promise<boolean>;
deleteBuffersByScope(scope: MemoryScope): Promise<number>;

@@ -60,0 +97,0 @@ saveWorkingMemory(scope: MemoryScope, snapshot: WorkingMemorySnapshot): Promise<void>;

@@ -1,4 +0,4 @@

import type { DocumentStore, SessionStore, VectorStore } from "./contracts";
export declare function createInMemoryDocumentStore(): DocumentStore;
import type { ProjectionCapableDocumentStore, SessionStore, VectorStore } from "./contracts";
export declare function createInMemoryDocumentStore(): ProjectionCapableDocumentStore;
export declare function createInMemorySessionStore(): SessionStore;
export declare function createInMemoryVectorStore(): VectorStore;

@@ -14,2 +14,3 @@ import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";

preferences: {
get?(id: string): Promise<PreferenceMemory | null>;
listByScope(scope: MemoryScope): Promise<PreferenceMemory[]>;

@@ -22,2 +23,3 @@ upsert(preference: PreferenceMemory): Promise<void>;

add(reference: ReferenceMemory): Promise<void>;
get?(id: string): Promise<ReferenceMemory | null>;
listByScope(scope: MemoryScope): Promise<ReferenceMemory[]>;

@@ -29,2 +31,3 @@ };

add(fact: FactMemory): Promise<void>;
get?(id: string): Promise<FactMemory | null>;
listByScope(scope: MemoryScope): Promise<FactMemory[]>;

@@ -35,2 +38,3 @@ };

feedback: {
get?(id: string): Promise<FeedbackMemory | null>;
listByScope(scope: MemoryScope): Promise<FeedbackMemory[]>;

@@ -43,2 +47,3 @@ upsert(feedback: FeedbackMemory): Promise<void>;

add(episode: EpisodeMemory): Promise<void>;
get?(id: string): Promise<EpisodeMemory | null>;
listByScope(scope: MemoryScope): Promise<EpisodeMemory[]>;

@@ -50,2 +55,3 @@ };

add(archive: SessionArchive): Promise<void>;
get?(id: string): Promise<SessionArchive | null>;
listByScope(scope: MemoryScope): Promise<SessionArchive[]>;

@@ -57,2 +63,3 @@ };

add(evidence: EvidenceRecord): Promise<void>;
get?(id: string): Promise<EvidenceRecord | null>;
listByScope(scope: MemoryScope): Promise<EvidenceRecord[]>;

@@ -59,0 +66,0 @@ };

@@ -1,2 +0,2 @@

import type { DocumentStore, SessionStore, VectorStore } from "./contracts";
import type { ProjectionCapableDocumentStore, SessionStore, VectorStore } from "./contracts";
export interface PostgresStorageConfig {

@@ -17,9 +17,41 @@ url: string;

}
export interface PostgresStorageMigrationEvent {
elapsedMs: number;
index: string;
schema: string;
status: "created" | "creating" | "current";
}
export interface PostgresStorageMigrationOptions {
log?: (event: PostgresStorageMigrationEvent) => void;
}
export interface PostgresDocumentIndexState {
definition: string;
isPartial: boolean;
isReady: boolean;
isUnique: boolean;
isValid: boolean;
method: string;
tableName: string;
tableSchema: string;
}
export interface PostgresStorageMigrationPort {
runExclusive<T>(operation: () => Promise<T>): Promise<T>;
createDocumentIndex(statement: string): Promise<void>;
ensureDocumentStore(): Promise<void>;
ensureVersionStore(): Promise<void>;
getDocumentIndex(indexName: string): Promise<PostgresDocumentIndexState | null>;
getVersion(): Promise<number | null>;
setVersion(version: number): Promise<void>;
}
export interface PostgresStorageMigrationDependencies {
port?: PostgresStorageMigrationPort;
}
interface PostgresStoreOptions {
readOnly?: boolean;
}
export declare function createPostgresDocumentStore(config: PostgresStorageConfig, options?: PostgresStoreOptions): DocumentStore;
export declare function createPostgresDocumentStore(config: PostgresStorageConfig, options?: PostgresStoreOptions): ProjectionCapableDocumentStore;
export declare function createPostgresSessionStore(config: PostgresStorageConfig, options?: PostgresStoreOptions): SessionStore;
export declare function createPostgresVectorStore(config: PostgresStorageConfig, options?: PostgresStoreOptions): VectorStore;
export declare function getPostgresVectorExtensionStatus(config: PostgresStorageConfig): Promise<PostgresVectorExtensionStatus>;
export declare function migratePostgresStorageBackend(config: PostgresStorageConfig, options?: PostgresStorageMigrationOptions, dependencies?: PostgresStorageMigrationDependencies): Promise<void>;
export declare function ensurePostgresStorageBackend(config: PostgresStorageConfig): Promise<void>;

@@ -26,0 +58,0 @@ export declare function probeReadOnlyPostgresStorageBackend(config: PostgresStorageConfig, dependencies?: ReadOnlyPostgresStorageProbeDependencies): Promise<ReadOnlyPostgresStorageProbeResult>;

@@ -1,2 +0,2 @@

import type { DocumentStore, SessionStore, VectorStore } from "./contracts";
import type { DocumentStore, ProjectionCapableDocumentStore, SessionStore, VectorStore } from "./contracts";
export interface PostgresStorageConfig {

@@ -7,2 +7,11 @@ url: string;

}
export interface PostgresStorageMigrationEvent {
elapsedMs: number;
index: string;
schema: string;
status: "created" | "creating" | "current";
}
export interface PostgresStorageMigrationOptions {
log?: (event: PostgresStorageMigrationEvent) => void;
}
interface PostgresStoreOptions {

@@ -16,8 +25,10 @@ readOnly?: boolean;

createPostgresVectorStore: (config: PostgresStorageConfig, options?: PostgresStoreOptions) => VectorStore;
migratePostgresStorageBackend: (config: PostgresStorageConfig, options?: PostgresStorageMigrationOptions) => Promise<void>;
};
export declare function setPostgresPublicModuleLoaderForTests(loader: (() => Promise<PostgresModule>) | null): void;
export declare function canBootstrapPostgresStorageBackend(config: PostgresStorageConfig): Promise<boolean>;
export declare function createPostgresDocumentStore(config: PostgresStorageConfig, options?: PostgresStoreOptions): DocumentStore;
export declare function migratePostgresStorageBackend(config: PostgresStorageConfig, options?: PostgresStorageMigrationOptions): Promise<void>;
export declare function createPostgresDocumentStore(config: PostgresStorageConfig, options?: PostgresStoreOptions): ProjectionCapableDocumentStore;
export declare function createPostgresSessionStore(config: PostgresStorageConfig, options?: PostgresStoreOptions): SessionStore;
export declare function createPostgresVectorStore(config: PostgresStorageConfig, options?: PostgresStoreOptions): VectorStore;
export {};

@@ -5,3 +5,3 @@ import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionBuffer, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";

import type { ExperienceRecord, LearningProposal, PromotionRecord, SessionArchive } from "../domain/evolutionRecords";
import type { DocumentStore, SessionStore, VectorRecord, VectorStore } from "./contracts";
import type { DocumentStore, SessionStore, VectorRecord, VectorSearchInput, VectorStore } from "./contracts";
export interface MemoryRepositoriesConfig {

@@ -19,2 +19,3 @@ documentStore: DocumentStore;

upsert(preference: PreferenceMemory): Promise<void>;
get(id: string): Promise<PreferenceMemory | null>;
listByUser(userId: string): Promise<PreferenceMemory[]>;

@@ -25,2 +26,3 @@ listByScope(scope: MemoryScope): Promise<PreferenceMemory[]>;

add(reference: ReferenceMemory): Promise<void>;
get(id: string): Promise<ReferenceMemory | null>;
listByUser(userId: string): Promise<ReferenceMemory[]>;

@@ -31,2 +33,3 @@ listByScope(scope: MemoryScope): Promise<ReferenceMemory[]>;

add(fact: FactMemory): Promise<void>;
get(id: string): Promise<FactMemory | null>;
listByUser(userId: string): Promise<FactMemory[]>;

@@ -37,2 +40,3 @@ listByScope(scope: MemoryScope): Promise<FactMemory[]>;

add(episode: EpisodeMemory): Promise<void>;
get(id: string): Promise<EpisodeMemory | null>;
listByUser(userId: string): Promise<EpisodeMemory[]>;

@@ -43,2 +47,3 @@ listByScope(scope: MemoryScope): Promise<EpisodeMemory[]>;

upsert(feedback: FeedbackMemory): Promise<void>;
get(id: string): Promise<FeedbackMemory | null>;
listByUser(userId: string): Promise<FeedbackMemory[]>;

@@ -98,6 +103,3 @@ listByScope(scope: MemoryScope): Promise<FeedbackMemory[]>;

}>): Promise<void>;
searchFactEmbedding(queryEmbedding: number[], input: {
topK: number;
filter?: Record<string, unknown>;
}): Promise<Array<{
searchFactEmbedding(queryEmbedding: number[], input: VectorSearchInput): Promise<Array<{
id: string;

@@ -117,6 +119,3 @@ embedding: number[];

}>): Promise<void>;
searchReferenceEmbedding(queryEmbedding: number[], input: {
topK: number;
filter?: Record<string, unknown>;
}): Promise<Array<{
searchReferenceEmbedding(queryEmbedding: number[], input: VectorSearchInput): Promise<Array<{
id: string;

@@ -136,6 +135,3 @@ embedding: number[];

}>): Promise<void>;
searchEpisodeEmbedding(queryEmbedding: number[], input: {
topK: number;
filter?: Record<string, unknown>;
}): Promise<Array<{
searchEpisodeEmbedding(queryEmbedding: number[], input: VectorSearchInput): Promise<Array<{
id: string;

@@ -142,0 +138,0 @@ embedding: number[];

import { Database } from "bun:sqlite";
import type { DocumentStore, SessionStore, VectorSearchResult, VectorStore } from "./contracts";
import type { ProjectionCapableDocumentStore, SessionStore, VectorSearchResult, VectorStore } from "./contracts";
import { type SQLiteExtensionLoadResult, type SQLiteRuntimeResolution, type SQLiteVectorExtensionConfig } from "./sqliteRuntime";

@@ -20,5 +20,5 @@ interface SQLiteStoreOptions {

}
export declare function createSQLiteDocumentStore(path: string, options?: SQLiteStoreOptions): DocumentStore;
export declare function createSQLiteDocumentStore(path: string, options?: SQLiteStoreOptions): ProjectionCapableDocumentStore;
export declare function createSQLiteSessionStore(path: string, options?: SQLiteStoreOptions): SessionStore;
export declare function createSQLiteVectorStore(path: string, options?: SQLiteStoreOptions, dependencies?: SQLiteVectorStoreDependencies): VectorStore;
export {};

@@ -1,2 +0,2 @@

import type { DocumentStore, SessionStore, StorageFilter, VectorSearchResult, VectorStore } from "./contracts";
import type { DocumentStore, ProjectionCapableDocumentStore, SessionStore, StorageFilter, VectorSearchResult, VectorStore } from "./contracts";
interface SQLiteStoreOptions {

@@ -24,5 +24,5 @@ readOnly?: boolean;

export declare function setSQLitePublicModuleLoaderForTests(loader: (() => Promise<SQLiteModule>) | null): void;
export declare function createSQLiteDocumentStore(path: string, options?: SQLiteStoreOptions): DocumentStore;
export declare function createSQLiteDocumentStore(path: string, options?: SQLiteStoreOptions): ProjectionCapableDocumentStore;
export declare function createSQLiteSessionStore(path: string, options?: SQLiteStoreOptions): SessionStore;
export declare function createSQLiteVectorStore(path: string, options?: SQLiteStoreOptions, dependencies?: SQLiteVectorStoreDependencies): VectorStore;
export {};
import type { EpisodeMemory, FactMemory, ReferenceMemory } from "../domain/records";
import { type LanguageService } from "../language";
import type { LanguageQueryAnalysis, LanguageService } from "../language";
export interface VerificationHint {

@@ -18,2 +18,3 @@ memoryId: string;

language?: LanguageService;
queryAnalysis?: LanguageQueryAnalysis;
}

@@ -33,3 +34,4 @@ export interface FactVerificationAssessment {

language?: LanguageService;
queryAnalysis?: LanguageQueryAnalysis;
}): number;
export declare function evaluateVerificationHints(input: VerificationPolicyInput): VerificationHint[];

@@ -12,4 +12,8 @@ # GoodMemory 15-Minute App Integration

The registry commands below apply after `goodmemory@0.7.0` is published. Before
publication, install the verified local `goodmemory-0.7.0.tgz` produced by the
release workflow.
```bash
npm install goodmemory
npm install goodmemory@0.7.0
```

@@ -20,3 +24,3 @@

```bash
bun add goodmemory
bun add goodmemory@0.7.0
```

@@ -23,0 +27,0 @@

# GoodMemory Claude Code Setup Guide
This is the canonical global CLI `0.6.0` Claude Code installed-host setup path.
This is the canonical global CLI `0.7.0` Claude Code installed-host setup path.

@@ -10,3 +10,3 @@ ## Install

```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory -V

@@ -23,3 +23,3 @@ ```

```bash
npm install -g ./goodmemory-0.6.0.tgz
npm install -g ./goodmemory-0.7.0.tgz
goodmemory -V

@@ -33,6 +33,10 @@ ```

```bash
goodmemory setup --host claude
goodmemory setup --host claude --default-locale en-US
goodmemory status claude --workspace-root .
```
Set `--default-locale` to the BCP-47 locale that Claude Code should use when a
prompt does not contain a distinctive language signal, for example `ko-KR`,
`fr-FR`, or `es-ES`.
This installs managed host wiring, enables workspace-scoped recall injection,

@@ -46,2 +50,6 @@ and keeps writeback opt-in. Use `observe` before durable `selective` writes:

`enable` reuses the global default locale selected by `setup`; it does not
override language configuration. Rerun setup with `--default-locale <locale>`
when that default must change.
## Package-Local Bootstrap

@@ -53,7 +61,7 @@

```bash
npm install goodmemory@0.6.0
npm install goodmemory@0.7.0
npx goodmemory claude bootstrap --user-id <user-id> --workspace-id <workspace-id>
```
Bun services can install the same package with `bun add goodmemory@0.6.0`.
Bun services can install the same package with `bun add goodmemory@0.7.0`.

@@ -60,0 +68,0 @@ This creates repo-local scaffolding only:

# GoodMemory Codex Handoff Setup Guide
This is the canonical global CLI `0.6.0` Codex installed-host setup path.
This is the canonical global CLI `0.7.0` Codex installed-host setup path.

@@ -10,3 +10,3 @@ ## Install

```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory -V

@@ -23,3 +23,3 @@ ```

```bash
npm install -g ./goodmemory-0.6.0.tgz
npm install -g ./goodmemory-0.7.0.tgz
goodmemory -V

@@ -33,6 +33,10 @@ ```

```bash
goodmemory setup --host codex
goodmemory setup --host codex --default-locale en-US
goodmemory status codex --workspace-root .
```
Set `--default-locale` to the BCP-47 locale that Codex should use when a prompt
does not contain a distinctive language signal, for example `ko-KR`, `fr-FR`,
or `es-ES`.
This installs managed host wiring, enables workspace-scoped recall injection,

@@ -46,2 +50,6 @@ and keeps writeback opt-in. Use `observe` before durable `selective` writes:

`enable` reuses the global default locale selected by `setup`; it does not
override language configuration. Rerun setup with `--default-locale <locale>`
when that default must change.
## Package-Local Bootstrap

@@ -53,7 +61,7 @@

```bash
npm install goodmemory@0.6.0
npm install goodmemory@0.7.0
npx goodmemory codex bootstrap --user-id <user-id> --workspace-id <workspace-id>
```
Bun services can install the same package with `bun add goodmemory@0.6.0`.
Bun services can install the same package with `bun add goodmemory@0.7.0`.

@@ -60,0 +68,0 @@ This creates repo-local scaffolding only:

@@ -664,2 +664,48 @@ # GoodMemory: First Principles and Reference Architecture

### 6.3.2 LanguagePack is a vertical semantic boundary
Language support crosses the full memory lifecycle. A locale-specific label
file is insufficient because extraction, retrieval, temporal meaning, entity
identity, and rendering must agree on the same semantics. Each `LanguagePack`
therefore owns detection, equality normalization, tokenization, bounded search
terms, query/content analysis, decomposition, temporal parsing, entity
extraction and matching, candidate extraction, and rendering.
The composition root resolves one pack for each operation and passes that
identity through remember, recall, projections, storage search, provenance, and
context construction. Core modules must not add parallel locale switches or
import concrete packs directly. Locale-specific lexicons, Unicode-script
checks, and natural-language rules belong under `src/language/**`; storage
receives derived search fields and does not interpret locale.
The first-class built-ins are English, Simplified Chinese, Traditional Chinese,
Japanese, Korean, French, and Spanish. Simplified and Traditional Chinese share implementation
primitives but deliberately use distinct compatibility groups and script-local
search analyzers. The 0.7 contract guarantees same-script recall, not
Simplified/Traditional cross-script lexical equivalence. Canonical source text
is never converted, and this boundary does not introduce OpenCC, a third-party
language detector, or a Japanese/Korean/Romance-language NLP runtime. Ambiguous
Han-only or unmarked Latin text resolves through the configured default;
unsupported explicit locales use neutral Unicode behavior rather than English
semantics.
`analyzerVersion` is a migration identity, not display metadata. Derived recall
documents record pack, analyzer, locale, and search-schema identity; any
semantic analyzer change requires a version bump and fail-closed projection
rebuild. Canonical memory remains raw and immutable with respect to search
normalization. Storage indexes admit candidates over derived `searchText`, while
application-level scoring remains the cross-backend ranking authority.
The stable `LanguageService` analyzer manifest covers resolver configuration,
all active packs, and custom-detector identity. An unversioned custom detector
cannot participate in a persistent completeness proof.
The 0.7 projection generation is versioned independently of canonical memory:
documents v3, entities v2, claims/status v2, and scope catalog v2. A per-scope
migration rebuilds from canonical sources, validates source and derived-record
coverage, then atomically publishes a complete catalog proof. Recall must not
consume a partial new generation; it uses the canonical fallback until cutover.
Migration is repeatable and does not rewrite canonical memory. This is a clean
breaking replacement of the former language adapter, with no compatibility
shim or dual-write period; see ADR-008 and the 0.6-to-0.7 migration guide.
### 6.4 Default vs optional capabilities

@@ -666,0 +712,0 @@

@@ -550,2 +550,23 @@ # GoodMemory PRD

### 12.11 FR-11 LanguagePack 横向扩展
GoodMemory 必须把语言支持实现为一个端到端语义边界,而不是散落在业务模块中的
locale 分支或翻译文件。
0.7 的产品契约是:
- `LanguagePack` 是唯一语言扩展点;不保留旧 language adapter 兼容层
- 一等支持 English、简体中文、繁体中文、日文、韩文、法文和西班牙文
- 同一 pack 负责检测、抽取、query/content analysis、时间表达、实体、搜索词和人类可读渲染
- remember、recall、answer、storage 和 installed-host 只能消费语言无关的结构化分析,不新增具体语言分支
- 未支持的显式 locale 使用 neutral Unicode 行为,不继承英文语义
- 简体和繁体分别保证同脚本写入与召回,不承诺简繁跨脚本词法召回
- 原始用户内容永远不转换;OpenCC、第三方语言检测器和日文 NLP 运行时不进入默认依赖
- analyzer、search schema 或 resolver identity 变化时,版本化派生 projection 必须 fail-closed 重建
- 新增自定义语言只注册完整 pack,并通过同一 conformance 与 `xx-Test` 端到端门禁,不修改业务模块
0.7 是干净 breaking release。升级必须完成 API/配置迁移、per-scope projection
重建和发布验证;不发布 adapter shim、dual-write 或半迁移状态。完整决策见
ADR-008,操作步骤见 `GoodMemory-0.6-to-0.7-Migration-Guide.md`。
---

@@ -552,0 +573,0 @@

@@ -41,3 +41,3 @@ # GoodMemory Python HTTP Integration Bridge

```bash
bun add goodmemory@0.6.0
bun add goodmemory@0.7.0

@@ -44,0 +44,0 @@ GOODMEMORY_HTTP_BRIDGE_TOKEN="replace-with-service-token" \

# GoodMemory Reference Integration Guide
This is the canonical packaged `0.6.0` reference path for chatbox/copilot-style integration.
This is the canonical packaged `0.7.0` reference path for chatbox/copilot-style integration.

@@ -10,3 +10,3 @@ ## Install

```bash
npm install goodmemory@0.6.0
npm install goodmemory@0.7.0
```

@@ -17,3 +17,3 @@

```bash
bun add goodmemory@0.6.0
bun add goodmemory@0.7.0
```

@@ -24,3 +24,3 @@

```bash
npm install ./goodmemory-0.6.0.tgz
npm install ./goodmemory-0.7.0.tgz
```

@@ -27,0 +27,0 @@

@@ -20,4 +20,8 @@ # GoodMemory Standalone MCP Setup Guide

The registry command below applies after `goodmemory@0.7.0` is published.
Before publication, install the verified local `goodmemory-0.7.0.tgz` produced
by the release workflow.
```bash
npm install -g goodmemory
npm install -g goodmemory@0.7.0
```

@@ -24,0 +28,0 @@

@@ -16,5 +16,10 @@ # GoodMemory Documentation Map

- `GoodMemory-TDD-and-Evaluation-Strategy.md` - test and eval strategy.
- `GoodMemory-Eval-Storage-Retention.md` - ephemeral eval Postgres isolation,
successful-run cleanup, failed-run retention, and operator commands.
## Architecture And Release Baselines
- `../adr/ADR-008-language-pack-horizontal-extension.txt` - accepted 0.7
LanguagePack boundary, breaking-replacement decision, script-local Chinese
guarantee, and versioned projection migration contract.
- `GoodMemory-OSS-Architecture-v1.md` - historical v1 package/module map; use

@@ -29,2 +34,6 @@ `GoodMemory-Current-Status-and-Evidence.md` for the current shipped surface.

- `GoodMemory-15-Minute-App-Integration.md` - shortest app integration path.
- `GoodMemory-LanguagePack-Extension-Guide.md` - built-in locale behavior,
custom language-pack contract, analyzer versioning, and projection migration.
- `GoodMemory-0.6-to-0.7-Migration-Guide.md` - breaking API/configuration,
projection cutover, validation, and rollback procedure for the 0.7 upgrade.
- `GoodMemory-Reference-Integration-Guide.md` - reference consumer pattern.

@@ -60,2 +69,6 @@ - `GoodMemory-Inspector-and-Admin-API.md` - local React Inspector, `/admin/v1`

implementation order, and public-claim gate; Claude Code is deferred.
- `plans/GoodMemory-Phase-74-Generalized-Memory-Core-Implementation.md` -
experimental generalized-memory implementation record, completed local
verification, scale evidence, and the still-unmet cross-benchmark promotion
boundary.
- `beam-instruction-following-diagnosis.md` - why BEAM instruction_following

@@ -62,0 +75,0 @@ 0.394 is a design tension (abstention vs world-knowledge), not a shaping bug.

@@ -13,2 +13,6 @@ # GoodMemory

Release source: this is the immutable GoodMemory 0.7.0 stable release source.
Registry commands require goodmemory@0.7.0 to be published. The release workflow
verifies npm latest and artifact integrity before creating the GitHub Release.
If you are an autonomous agent reading this to decide whether to give *yourself*

@@ -25,3 +29,3 @@ memory: yes, that is a supported first-class path. Start with the decision tree

```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory setup # detects Codex + Claude Code, installs managed wiring

@@ -84,3 +88,4 @@ goodmemory status

Current `v0.6.0` public-opt-in claims:
Versioned `v0.6.0` evidence retained for the `v0.7.0` line; these are not
current `v0.7.0` production claims until rerun:

@@ -93,3 +98,3 @@ - [LoCoMo full 10](https://github.com/hjqcan/GoodMemory/blob/main/benchmark-claims/locomo.json): official 0.8708, strict 0.6299, open-domain 0.6146 (59/96); provider-backed recommended profile; dataset CC BY-NC 4.0.

- [LongMemEval full 500](https://github.com/hjqcan/GoodMemory/blob/main/benchmark-claims/longmemeval.json): historical strict 0.720 and official-protocol 0.888.
- [LongMemEval full 500](https://github.com/hjqcan/GoodMemory/blob/main/benchmark-claims/longmemeval.json): historical strict 0.720 and official-prompt-compatible 0.888; the latter is not directly comparable to published official scores because its gpt-5.4 judge is outside the pinned evaluator model zoo.
- [ImplicitMemBench Full-300](https://github.com/hjqcan/GoodMemory/blob/main/benchmark-claims/implicitmembench.json): historical stored-answer 0.691 versus baseline 0.400.

@@ -96,0 +101,0 @@

{
"name": "goodmemory",
"version": "0.6.0",
"version": "0.7.0",
"goodmemoryRelease": {
"installCommandsApplyAfterPublish": true,
"npmDistTag": "latest",
"status": "stable"
},
"mcpName": "io.github.hjqcan/goodmemory",

@@ -44,2 +49,3 @@ "description": "Memory layer for chat, copilot, and agent applications.",

"docs/GoodMemory-15-Minute-App-Integration.md",
"docs/GoodMemory-0.6-to-0.7-Migration-Guide.md",
"docs/GoodMemory-Claude-Code-Setup-Guide.md",

@@ -51,2 +57,3 @@ "docs/GoodMemory-Codex-Handoff-Setup-Guide.md",

"docs/GoodMemory-Inspector-and-Admin-API.md",
"docs/GoodMemory-LanguagePack-Extension-Guide.md",
"docs/GoodMemory-MCP-Registry-Publishing.md",

@@ -106,2 +113,3 @@ "docs/GoodMemory-OpenCode-Setup-Guide.md",

"test:all": "bun --config=bunfig.all.toml test tests third-party",
"test:phase-73-gates": "bun --config=bunfig.phase-73-gates.toml test ./tests/quality-gates/phase-73/*.gate.ts",
"test:unit": "bun test tests/unit",

@@ -132,2 +140,3 @@ "test:integration": "bun test tests/integration",

"eval:fallback": "bun run scripts/run-eval.ts --mode=fallback",
"eval:storage:cleanup": "bun run scripts/cleanup-eval-postgres.ts",
"eval:official-rescore": "bun run scripts/rescore-official-protocols.ts",

@@ -248,2 +257,10 @@ "audit:phase-61-implicitmembench-rescore-readiness": "bun run scripts/audit-phase-61-implicitmembench-rescore-readiness.ts",

"record:codex-coding-effect:c4-review": "bun run scripts/record-codex-coding-effect-c4-review-provenance.ts",
"prepare:codex-coding-effect:c5-pilot": "bun run scripts/prepare-codex-coding-effect-c5-pilot.ts",
"eval:codex-coding-effect:c5-canary": "bun run scripts/run-codex-coding-effect-c5-canary.ts",
"eval:codex-coding-effect:c5-pilot": "bun run scripts/run-codex-coding-effect-c5-pilot.ts",
"project:codex-coding-effect:c5-evidence": "bun run scripts/project-codex-coding-effect-c5-evidence.ts",
"verify:codex-coding-effect:c5-evidence": "bun run scripts/verify-codex-coding-effect-c5-evidence.ts",
"prepare:codex-coding-effect:c5-review": "bun run scripts/prepare-codex-coding-effect-c5-review.ts",
"record:codex-coding-effect:c5-review": "bun run scripts/record-codex-coding-effect-c5-review-provenance.ts",
"gate:codex-coding-effect:c5": "bun run scripts/run-codex-coding-effect-c5-gate.ts",
"project:codex-coding-effect:c2-evidence": "bun run scripts/project-codex-coding-effect-c2-evidence.ts",

@@ -258,2 +275,8 @@ "eval:phase-72-beam-generalization-live": "bun run scripts/run-phase-72-beam-generalization-live.ts",

"eval:phase-72-minteval-smoke": "bun run scripts/run-phase-72-minteval-smoke.ts",
"eval:phase-74-generalization": "bun run scripts/run-phase-74-generalization.ts",
"eval:phase-74-beam-safety": "bun run scripts/run-phase-74-beam-safety-protection.ts",
"eval:phase-74-protection-evidence": "bun run scripts/build-phase-74-protection-evidence.ts",
"aggregate:phase-74-generalization": "bun run scripts/aggregate-phase-74-generalization.ts",
"prepare:phase-74-datasets": "bun run scripts/prepare-phase-74-datasets.ts",
"gate:phase-74-storage-scale": "bun run scripts/run-phase-74-storage-scale-gate.ts",
"merge:phase-72-implicitmembench-retry": "bun run scripts/merge-phase-72-implicitmembench-retry.ts",

@@ -315,2 +338,3 @@ "prepare:phase-72-beam-stored-retry": "bun run scripts/prepare-phase-72-beam-stored-retry.ts",

"gate:v0-3-release-readiness": "bun run scripts/run-v0-3-release-readiness.ts",
"gate:v0.7": "bun run scripts/run-v0-7-release-readiness.ts",
"gate:public-benchmark-claim": "bun run scripts/run-public-benchmark-claim-gate.ts",

@@ -317,0 +341,0 @@ "gate:phase-68": "bun run scripts/run-phase-68-generalization-gate.ts",

+136
-29

@@ -7,2 +7,7 @@ # GoodMemory

> **Release source:** this is the immutable `0.7.0` stable release source.
> Registry commands require `goodmemory@0.7.0` to be published. The release
> workflow verifies npm `latest` and artifact integrity before creating the
> GitHub Release.
It gives chat apps, copilots, and agent hosts a durable user/project memory loop:

@@ -34,6 +39,50 @@ write selected facts, retrieve the right context, inject it into the next turn,

## OpenAI Build Week 2026
**Pre-existing foundation.** GoodMemory existed before OpenAI Build Week. The
pre-event foundation already included the core memory API, local
SQLite/Postgres storage, installed-host integration, and the local Inspector.
The hackathon entry is the work added after the submission period opened on
July 13, 2026, not the entire repository.
**Added during Build Week.** Dated commits completed and published `v0.6.0`,
strengthened generalized retrieval and iterative-recall verification, added
claim-source provenance coverage, hardened installed-host canaries and leakage
audits, and expanded the controlled Codex coding-effect evaluation path. Review
the [pre-event-to-Build-Week diff](https://github.com/hjqcan/GoodMemory/compare/373e1f9a...5d7639a8)
and its dated commit history for the exact boundary.
**How Codex and GPT-5.6 were used.** Codex with GPT-5.6 was the primary
implementation and verification environment: exploring the repository,
implementing and reviewing changes, writing regression tests, reproducing
installed-host behavior, and exercising the release and coding-effect evidence
paths. GPT-5.6 also powers disclosed non-judge model calls in current evaluation
profiles; public-claim paths either use deterministic scoring or keep the judge
independent from the answer model.
**Run and verify.** Install the submitted release and inspect its local memory
surface:
```bash
npm install -g goodmemory@0.7.0
goodmemory setup --host codex
goodmemory status codex --workspace-root .
goodmemory inspector serve
```
Verify the repository from source with `bun install --frozen-lockfile`,
`bun test`, and `bun run typecheck`. See the
[Devpost submission](https://devpost.com/software/goodmemory) and
[public demo video](https://youtu.be/xK663ultN5o).
**Claim boundary:** the submission demonstrates durable cross-session memory,
governed writeback, recall evidence, and inspection/deletion infrastructure. It
does not claim that GoodMemory has already proven an improvement in Codex
coding outcomes; that paired hidden-test evaluation remains an active,
fail-closed evidence track.
## Start Here: Codex Or Claude Code
```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory setup

@@ -61,5 +110,8 @@ ```

The Phase 72 benchmark and versioned release gates are closed for `v0.6.0`.
The current rows below are public-opt-in results for the disclosed provider-backed
or evidence-pack profiles. They are not claims about the zero-provider default.
The Phase 72 benchmark and versioned release gates remain closed evidence for
`v0.6.0`. The rows below preserve those version-pinned public-opt-in results for
the disclosed provider-backed or evidence-pack profiles. Because `v0.7.0`
changes LanguagePack and recall semantics, they remain historical 0.6 evidence,
not 0.7 performance claims or claims about the zero-provider default; no row is
promoted as a current `v0.7.0` claim until a fresh run passes the same gate.
LongMemEval's newer label-free verifier result and ImplicitMemBench's retry-merged

@@ -73,5 +125,2 @@ result remain internal evidence because their current paths are eval-only or do

|---|---|---:|---:|---|
| LoCoMo (full 10 conversations) | independent official judge protocol; strict deterministic token-F1 | official **0.8708** · strict **0.6299** · open-domain **0.6146** (59/96) | historical no-memory 0.0045 | [locomo.json](./benchmark-claims/locomo.json) |
| BEAM 100K (400 questions, 1051 rubric items) | independent official unified rubric; strict binary disclosed separately | unified **0.7651** · strict **0.620** (248/400) · generalized recall **0.8276** | public full-400 same-protocol reference 0.49 | [beam.json](./benchmark-claims/beam.json) |
| MemoryAgentBench (CR, TTL) | deterministic upstream match-mode scoring, judge-free | **CR 0.959, TTL 0.933** | no-memory 0.000 for both | [memoryagentbench.json](./benchmark-claims/memoryagentbench.json) |
<!-- current-claims-table:end -->

@@ -81,4 +130,6 @@

These rows remain reproducible evidence for the disclosed package version and
runtime profile. They are not current-production claims for `v0.6.0`.
These rows are versioned attestations with tracked source fingerprints for the
disclosed package version and runtime profile. Reproduction also requires the
referenced raw artifacts, which are not all stored in the Git tree. They are
not current-production claims for `v0.7.0`.

@@ -88,3 +139,6 @@ <!-- historical-evidence-table:start -->

|---|---|---:|---:|---|
| LongMemEval full 500 | strict: judge-free deterministic subset · comparable: official LongMemEval judge protocol | strict **0.720** (360/500) · official-protocol **0.888** (444/500), `goodmemory-rules-only` | no-memory 0.068; current Mem0 harness: 94.4 Top200 / 94.8 Top50 (different stack and budget) | [longmemeval.json](./benchmark-claims/longmemeval.json) |
| LoCoMo v0.6.0 (full 10 conversations) | independent official judge protocol; strict deterministic token-F1 | official **0.8708** · strict **0.6299** · open-domain **0.6146** (59/96) | historical no-memory 0.0045 | [locomo.json](./benchmark-claims/locomo.json) |
| BEAM 100K v0.6.0 (400 questions, 1051 rubric items) | independent official unified rubric; strict binary disclosed separately | unified **0.7651** · strict **0.620** (248/400) · generalized recall **0.8276** | public full-400 same-protocol reference 0.49 | [beam.json](./benchmark-claims/beam.json) |
| MemoryAgentBench v0.6.0 (CR, TTL) | deterministic upstream match-mode scoring, judge-free | **CR 0.959, TTL 0.933** | no-memory 0.000 for both | [memoryagentbench.json](./benchmark-claims/memoryagentbench.json) |
| LongMemEval full 500 | strict: judge-free deterministic subset · diagnostic: official-prompt-compatible LongMemEval judge | strict **0.720** (360/500) · prompt-compatible **0.888** (444/500), `goodmemory-rules-only` | no-memory 0.068; current Mem0 harness: 94.4 Top200 / 94.8 Top50 (different stack and budget) | [longmemeval.json](./benchmark-claims/longmemeval.json) |
| ImplicitMemBench Full-300 | stored-answer cross-version judge rescore | **0.691** (207.35/300), gpt-5.4 judge over gpt-5.5 answers, sourceAnswersUnchanged | upstream-chat baseline **0.400** (120/300); reference line 0.66 | [implicitmembench.json](./benchmark-claims/implicitmembench.json) |

@@ -95,8 +149,9 @@ <!-- historical-evidence-table:end -->

**strict** track is deterministic or judge-free — a hard lower bound no LLM
judge can inflate. The **comparable** track re-judges the *same stored answers*
(not regenerated) under each benchmark's official or industry-standard judge
protocol, verbatim, so the number sits on the same scale as published
competitor results. The gap between the tracks is quantified judge leniency,
disclosed instead of hidden. Every per-protocol detail is recorded in the
linked declarations.
judge can inflate. The second track re-judges the *same stored answers* (not
regenerated) under a benchmark-source or industry-standard prompt. Numerical
comparability is claimed only when the pinned evaluator model and remaining
benchmark configuration also match. LongMemEval's gpt-5.4/gpt-5.5 diagnostics
are outside the pinned evaluator model zoo and are therefore
prompt-compatible, not directly comparable to published official scores.
Every per-protocol detail is recorded in the linked declarations.

@@ -116,3 +171,3 @@ The historical LongMemEval strict result is judge-free, replacing an earlier

[claim declaration](./benchmark-claims/longmemeval.json).
The current MemoryAgentBench claim is deliberately scoped. It uses
The historical v0.6.0 MemoryAgentBench evidence is deliberately scoped. It uses
`gpt-5.6-terra` answers and deterministic, judge-free upstream match-mode

@@ -125,3 +180,3 @@ scoring. Conflict Resolution scores CR 0.959 (70/73) and Test-Time Learning

The current LoCoMo claim covers all 1540 non-adversarial questions with
The historical v0.6.0 LoCoMo evidence covers all 1540 non-adversarial questions with
`executionFailures: 0`. It uses `gpt-5.6-terra` for answers, conversational

@@ -136,3 +191,3 @@ extraction, and provider reranking, then uses an independent `gpt-5.5` judge

The current BEAM claim uses `gpt-5.6-terra` answers and an independent
The historical v0.6.0 BEAM evidence uses `gpt-5.6-terra` answers and an independent
`gpt-5.5` judge. The generalized path disables all 148 legacy narrow gates and

@@ -166,3 +221,5 @@ legacy fitted answer postprocessing. It reaches 0.8276 evidence recall and

LongMemEval's Phase 72 eval-only verifier chain reaches 0.720 judge-free and
0.924 under an independent official-protocol judge, but it is not a production
0.924 under an independent gpt-5.5 official-prompt-compatible judge. That model
is outside the pinned LongMemEval evaluator model zoo, so the result is not
directly comparable to published official scores; it is also not a production
runtime profile. ImplicitMemBench's explicit retry-merged check reaches

@@ -195,3 +252,3 @@ 0.6923666667 with zero failures, but it is not a replacement monolithic fresh

- **You are, or run inside, Claude Code or Codex** →
`npm install -g goodmemory@0.6.0 && goodmemory setup`. Unsure what is already
`npm install -g goodmemory@0.7.0 && goodmemory setup`. Unsure what is already
wired? Run `goodmemory adopt` (add `--json` for a machine-readable plan): it

@@ -304,3 +361,4 @@ inspects `.claude/`, `.codex/`, and existing MCP config, then prints the exact

GoodMemory `0.6.0` has two normal install paths.
After GoodMemory `0.7.0` is published, it has two normal registry install paths.
Before publication, use the tarball verification path below.

@@ -311,3 +369,3 @@ Use the global CLI when you want memory enhancement inside installed coding

```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory setup

@@ -320,7 +378,7 @@ goodmemory status

```bash
npm install goodmemory@0.6.0
npm install goodmemory@0.7.0
```
If you want to type `goodmemory` directly, install the global CLI.
A project-local `npm install goodmemory@0.6.0` does not put `goodmemory` on your shell `PATH`.
A project-local `npm install goodmemory@0.7.0` does not put `goodmemory` on your shell `PATH`.
Use `npx goodmemory`, `npm exec -- goodmemory`, or `./node_modules/.bin/goodmemory`

@@ -336,3 +394,3 @@ from that project instead.

```bash
bun add goodmemory@0.6.0
bun add goodmemory@0.7.0
```

@@ -343,3 +401,3 @@

```bash
npm install ./goodmemory-0.6.0.tgz
npm install ./goodmemory-0.7.0.tgz
```

@@ -356,3 +414,3 @@

```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory setup

@@ -634,2 +692,34 @@ goodmemory status

### Locale and LanguagePack
Built-in packs cover English, Simplified Chinese, Traditional Chinese
(`zh-TW`/`zh-HK`/`zh-MO`), Japanese, Korean, French, and Spanish. Set a
host-known locale explicitly; otherwise auto-detection falls back to
`defaultLocale` for inherently ambiguous Han-only or unmarked Latin text.
```ts
const multilingualMemory = createGoodMemory({
language: {
defaultLocale: "zh-TW",
detection: "auto",
},
});
await multilingualMemory.remember({
locale: "ko-KR",
scope,
messages: [{ role: "user", content: "현재 역할은 릴리스 책임자입니다." }],
});
```
Adding a language means implementing one complete `LanguagePack`, not adding
module-local regex branches. See the
[LanguagePack extension guide](./docs/GoodMemory-LanguagePack-Extension-Guide.md)
for the contract, custom registration, analyzer versioning, and projection
migration rules.
Upgrading from the previous adapter/projection contract is intentionally
breaking; follow the
[0.6 to 0.7 migration guide](./docs/GoodMemory-0.6-to-0.7-Migration-Guide.md).
For production app integrations, the recommended turn loop adds the governed

@@ -891,2 +981,14 @@ runtime layer around that core:

Custom `DocumentStore` adapters keep the original set/get/update/query/delete
contract. Projection-backed features such as the `recommended` generalized
fusion preset additionally require `ProjectionCapableDocumentStore`, whose
`projectionBatchSemantics` must equal the exported
`PROJECTION_BATCH_SEMANTICS` version and whose
`writeBatchIfUnchanged()` must atomically validate `expected`/`unchanged` rows
and apply every `set` and `delete` in the batch. Existing adapters can continue
to run without projections; a legacy same-named method is deliberately not
treated as the current atomic contract. Add the version marker only after the
adapter implements the full semantics. The built-in memory, SQLite, and
Postgres stores already implement it.
Inspect the resolved runtime instead of guessing:

@@ -1148,3 +1250,3 @@

The `goodmemory` command on your shell `PATH` is the global CLI installed with
`npm install -g goodmemory@0.6.0`. In a local dependency install, invoke the
`npm install -g goodmemory@0.7.0`. In a local dependency install, invoke the
package bin as `npx goodmemory`, `npm exec -- goodmemory`, or

@@ -1244,2 +1346,4 @@ `./node_modules/.bin/goodmemory`. The repo-local `bun run goodmemory` script is

[docs/GoodMemory-Reference-Integration-Guide.md](./docs/GoodMemory-Reference-Integration-Guide.md)
- LanguagePack extension guide:
[docs/GoodMemory-LanguagePack-Extension-Guide.md](./docs/GoodMemory-LanguagePack-Extension-Guide.md)
- Codex handoff setup guide:

@@ -1294,2 +1398,5 @@ [docs/GoodMemory-Codex-Handoff-Setup-Guide.md](./docs/GoodMemory-Codex-Handoff-Setup-Guide.md)

For the complete 0.7 package, coverage, runtime-consumer, size, and provenance
gate, run `bun run gate:v0.7 --strict`.
Use `bun run test:all` only when you intentionally want the broader sweep

@@ -1296,0 +1403,0 @@ through vendored or third-party test trees.

@@ -7,2 +7,6 @@ # GoodMemory

> **发布源码:**这是不可变的 `0.7.0` 稳定发布源码。Registry 命令要求
> `goodmemory@0.7.0` 已发布;release workflow 会先校验 npm `latest`
> 与制品完整性,再创建 GitHub Release。
它为 chat app、copilot 和 agent host 提供一条可审计的用户/项目记忆闭环:

@@ -25,3 +29,3 @@ 选择性写入事实,检索正确上下文,注入下一轮对话,记录发生过什么,并在记忆错误时删除。

```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory setup

@@ -39,8 +43,10 @@ ```

当前包版本的已提交 declaration 通过 `gate:public-benchmark-claim --strict` 后,才能进入
当前声明表:完整覆盖、`executionFailures: 0`、无记忆基线、确定性评分或独立判官、数据集
来源与 license 已核实、运行可复现(commit + 命令 + 包版本)。历史行使用独立 marker,
不能满足当前版本 gate。
当前声明表。该 gate 校验声明结构、相对基线的方向、answer/judge 分离、完整 commit、证据
投影断言与 README 一致性;它不是对上游 license 或被忽略原始报告的独立复现。历史行使用
独立 marker 和源文件指纹,复现仍需要取得对应原始 artifact,且不能满足当前版本 gate。
Phase 72 的 benchmark gate 和带版本 release gate 已为 `v0.6.0` 收口。下面三行是
明确披露 profile 的 public-opt-in 当前结果,不代表零 provider 默认路径。
Phase 72 的 benchmark gate 和带版本 release gate 仍是 `v0.6.0` 的有效历史证据。
下面三行保留明确披露 profile 的 0.6 public-opt-in 结果。由于 `v0.7.0` 改变了
LanguagePack 与召回语义,它们对 0.7 包而言只是历史证据,不是 0.7 性能声明,也不代表
零 provider 默认路径;在新版本完成同等 fresh run 之前,当前声明表保持为空。
LongMemEval 的新 verifier 结果与 ImplicitMemBench 的 retry-merged 结果仍属于内部

@@ -53,5 +59,2 @@ 证据,因为前者是 eval-only 路径,后者不能替代一次全新的单体 Full-300 运行。

|---|---|---:|---:|---|
| LoCoMo(完整 10 会话) | 独立官方判官协议;strict 确定性 token-F1 | official **0.8708** · strict **0.6299** · open-domain **0.6146**(59/96) | 历史无记忆 0.0045 | [locomo.json](./benchmark-claims/locomo.json) |
| BEAM 100K(400 题、1051 条 rubric) | 独立官方 unified rubric;另行披露 strict binary | unified **0.7651** · strict **0.620**(248/400)· 泛化 recall **0.8276** | 公开 full-400 同协议参照 0.49 | [beam.json](./benchmark-claims/beam.json) |
| MemoryAgentBench (CR, TTL) | 上游确定性 match-mode,judge-free | **CR 0.959, TTL 0.933** | 两项无记忆均为 0.000 | [memoryagentbench.json](./benchmark-claims/memoryagentbench.json) |
<!-- current-claims-table:end -->

@@ -64,3 +67,6 @@

|---|---|---:|---:|---|
| LongMemEval full 500 | 严格轨:judge-free 确定性子集 · 可比轨:官方 LongMemEval 判官协议 | 严格 **0.720**(360/500)· 官方协议 **0.888**(444/500),`goodmemory-rules-only` | 无记忆 0.068;当前 Mem0 harness:94.4 Top200 / 94.8 Top50(模型栈与预算不同) | [longmemeval.json](./benchmark-claims/longmemeval.json) |
| LoCoMo v0.6.0(完整 10 会话) | 独立官方判官协议;strict 确定性 token-F1 | official **0.8708** · strict **0.6299** · open-domain **0.6146**(59/96) | 历史无记忆 0.0045 | [locomo.json](./benchmark-claims/locomo.json) |
| BEAM 100K v0.6.0(400 题、1051 条 rubric) | 独立官方 unified rubric;另行披露 strict binary | unified **0.7651** · strict **0.620**(248/400)· 泛化 recall **0.8276** | 公开 full-400 同协议参照 0.49 | [beam.json](./benchmark-claims/beam.json) |
| MemoryAgentBench v0.6.0 (CR, TTL) | 上游确定性 match-mode,judge-free | **CR 0.959, TTL 0.933** | 两项无记忆均为 0.000 | [memoryagentbench.json](./benchmark-claims/memoryagentbench.json) |
| LongMemEval full 500 | 严格轨:judge-free 确定性子集 · 诊断轨:LongMemEval 官方 prompt 兼容判官 | 严格 **0.720**(360/500)· prompt-compatible **0.888**(444/500),`goodmemory-rules-only` | 无记忆 0.068;当前 Mem0 harness:94.4 Top200 / 94.8 Top50(模型栈与预算不同) | [longmemeval.json](./benchmark-claims/longmemeval.json) |
| ImplicitMemBench Full-300 | stored-answer cross-version judge rescore | **0.691**(207.35/300),gpt-5.4 judge over gpt-5.5 answers,sourceAnswersUnchanged | upstream-chat 基线 **0.400**(120/300);reference line 0.66 | [implicitmembench.json](./benchmark-claims/implicitmembench.json) |

@@ -70,6 +76,7 @@ <!-- historical-evidence-table:end -->

在两条轨都存在时会同时报告它们。**严格轨**是确定性或 judge-free 评分——任何 LLM 判官
都无法夸大的硬下限。**可比轨**把*同一批已存答案*(不重新生成)用该基准的
官方或业界标准判官协议逐字重判,使数字与已发表的竞品结果同尺可比。两轨
之间的差距就是被量化的判官宽松度——披露而不是隐藏。每个协议细节都记录在
链接的 claim declaration 里。
都无法夸大的硬下限。第二条轨把*同一批已存答案*(不重新生成)用基准来源或业界标准
prompt 重判。只有 evaluator model 与其余冻结配置也匹配时,才主张数值可比。LongMemEval
的 gpt-5.4/gpt-5.5 诊断不在 pinned evaluator model zoo 中,因此只能称 prompt-compatible,
不能与 published official score 直接数值比较。每个协议细节都记录在链接的 claim
declaration 里。

@@ -85,3 +92,3 @@ 历史 LongMemEval 严格结果是 judge-free 的,取代了此前一个已作废、不可声明的内部带判官数字(0.908)。

[claim declaration](./benchmark-claims/longmemeval.json)。
当前 MemoryAgentBench 声明刻意限定范围。答案由 `gpt-5.6-terra` 生成,评分采用
历史 v0.6.0 MemoryAgentBench 证据刻意限定范围。答案由 `gpt-5.6-terra` 生成,评分采用
上游确定性 match-mode,属于 judge-free。Conflict Resolution 得 CR 0.959

@@ -92,3 +99,3 @@ (70/73),Test-Time Learning 得 TTL 0.933(28/30),无记忆 arm 在两项上均为

当前 LoCoMo 声明覆盖全部 1540 道非对抗题,`executionFailures: 0`。答案、对话式
历史 v0.6.0 LoCoMo 证据覆盖全部 1540 道非对抗题,`executionFailures: 0`。答案、对话式
萃取与 provider reranking 使用 `gpt-5.6-terra`,官方协议轨由独立

@@ -100,3 +107,3 @@ `gpt-5.5` 判官评分。official 为 0.8708,strict 确定性 token-F1 为 0.6299,

当前 BEAM 声明使用 `gpt-5.6-terra` 回答和独立 `gpt-5.5` 判官。泛化路径关闭
历史 v0.6.0 BEAM 证据使用 `gpt-5.6-terra` 回答和独立 `gpt-5.5` 判官。泛化路径关闭
全部 148 个 legacy narrow gate 与 fitted answer 后处理,evidence recall 为

@@ -125,4 +132,6 @@ 0.8276;全部 400 题、1051 条 official rubric 的 unified 得分为 0.7651,对照

LongMemEval 的 Phase 72 eval-only verifier chain 达到 judge-free 0.720、独立官方
协议 0.924,但它不是生产 runtime profile。ImplicitMemBench 的显式 retry-merged
LongMemEval 的 Phase 72 eval-only verifier chain 达到 judge-free 0.720、独立 gpt-5.5
官方 prompt 兼容评分 0.924。gpt-5.5 不在 pinned LongMemEval evaluator model zoo 中,
所以该结果不能与 published official score 直接数值比较;它也不是生产 runtime
profile。ImplicitMemBench 的显式 retry-merged
检查达到 0.6923666667 且零失败,但不能替代一次全新的单体 Full-300 运行,因此两者

@@ -149,3 +158,3 @@ 都不进入 current-claims table。底层报告位于 gitignored 的 `reports/` 下,可按记录

- **你是、或运行在 Claude Code / Codex 里** →
`npm install -g goodmemory@0.6.0 && goodmemory setup`。不确定环境里已经装了
`npm install -g goodmemory@0.7.0 && goodmemory setup`。不确定环境里已经装了
什么?运行 `goodmemory adopt`(加 `--json` 得到机器可读方案):它会检测

@@ -245,3 +254,3 @@ `.claude/`、`.codex/` 和已有的 MCP 配置,并打印出针对你环境的确切下一条命令。

GoodMemory `0.6.0` 有两条常用安装路径。
GoodMemory `0.7.0` 有两条常用安装路径。

@@ -251,3 +260,3 @@ 如果你想给已安装的 coding agent 增加记忆能力,使用全局 CLI:

```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory setup

@@ -260,7 +269,7 @@ goodmemory status

```bash
npm install goodmemory@0.6.0
npm install goodmemory@0.7.0
```
如果你想直接输入 `goodmemory`,必须安装全局 CLI。
项目内 `npm install goodmemory@0.6.0` 不会把 `goodmemory` 放进 shell 的 `PATH`。
项目内 `npm install goodmemory@0.7.0` 不会把 `goodmemory` 放进 shell 的 `PATH`。
这种本地依赖安装只能从该项目里用 `npx goodmemory`、

@@ -276,3 +285,3 @@ `npm exec -- goodmemory` 或 `./node_modules/.bin/goodmemory` 调用。

```bash
bun add goodmemory@0.6.0
bun add goodmemory@0.7.0
```

@@ -283,3 +292,3 @@

```bash
npm install ./goodmemory-0.6.0.tgz
npm install ./goodmemory-0.7.0.tgz
```

@@ -294,3 +303,3 @@

```bash
npm install -g goodmemory@0.6.0
npm install -g goodmemory@0.7.0
goodmemory setup

@@ -535,2 +544,30 @@ goodmemory status

### Locale 与 LanguagePack
内置语言包覆盖英文、简体中文、繁体中文(`zh-TW`/`zh-HK`/`zh-MO`)、日文、
韩文、法文和西班牙文。host 已知 locale 时应显式传入;未传入时会自动检测,而
纯汉字或没有语言标记的拉丁字母文本会回退到 `defaultLocale`,不会强行猜测。
```ts
const multilingualMemory = createGoodMemory({
language: {
defaultLocale: "zh-TW",
detection: "auto",
},
});
await multilingualMemory.remember({
locale: "ko-KR",
scope,
messages: [{ role: "user", content: "현재 역할은 릴리스 책임자입니다." }],
});
```
新增语言需要实现一个完整的 `LanguagePack`,不能在各模块继续添加 locale 分支。
完整契约、自定义注册、analyzer 版本与 projection 迁移规则见
[LanguagePack 扩展指南](./docs/GoodMemory-LanguagePack-Extension-Guide.md)。
从旧 adapter/projection 契约升级是有意的 breaking change,请按
[0.6 到 0.7 迁移指南](./docs/GoodMemory-0.6-to-0.7-Migration-Guide.md)执行。
生产应用接入时,推荐的 turn loop 会在这个核心闭环外增加受治理的

@@ -954,3 +991,3 @@ runtime 层:

shell `PATH` 上的裸 `goodmemory` 命令来自
`npm install -g goodmemory@0.6.0` 安装的全局 CLI。本地 dependency install
`npm install -g goodmemory@0.7.0` 安装的全局 CLI。本地 dependency install
里,用 `npx goodmemory`、`npm exec -- goodmemory` 或

@@ -1048,2 +1085,3 @@ `./node_modules/.bin/goodmemory` 调用 package bin。repo-local

- Reference integration guide:[docs/GoodMemory-Reference-Integration-Guide.md](./docs/GoodMemory-Reference-Integration-Guide.md)
- LanguagePack 扩展指南:[docs/GoodMemory-LanguagePack-Extension-Guide.md](./docs/GoodMemory-LanguagePack-Extension-Guide.md)
- Codex handoff setup guide:[docs/GoodMemory-Codex-Handoff-Setup-Guide.md](./docs/GoodMemory-Codex-Handoff-Setup-Guide.md)

@@ -1088,2 +1126,5 @@ - Claude Code setup guide:[docs/GoodMemory-Claude-Code-Setup-Guide.md](./docs/GoodMemory-Claude-Code-Setup-Guide.md)

0.7 发布前用 `bun run gate:v0.7 --strict` 统一验证 package、coverage、
runtime consumer、体积与 benchmark 版本溯源。
只有当你明确需要覆盖 vendored 或 third-party test trees 时,才使用 `bun run test:all`。

@@ -1090,0 +1131,0 @@

@@ -11,3 +11,3 @@ {

},
"version": "0.6.0",
"version": "0.7.0",
"packages": [

@@ -18,3 +18,3 @@ {

"identifier": "goodmemory",
"version": "0.6.0",
"version": "0.7.0",
"runtimeHint": "npx",

@@ -21,0 +21,0 @@ "transport": {

Sorry, the diff of this file is too big to display

import{qb as F,rb as N,tb as x}from"./chunk-ve2dyh5j.js";import"./chunk-xmaks7z1.js";import{SQL as b}from"bun";var g="public",f="gm",E="gm_documents",R="gm_session_state",v=/^[A-Za-z_][A-Za-z0-9_]*$/,I=new Map;function d(O){let H=O.trim();if(H.length===0)throw Error("Postgres storage requires a non-empty url");return H}function J(O,H){if(!v.test(O))throw Error(`Invalid Postgres ${H}: ${O}. Use only letters, digits, and underscores, and start with a letter or underscore.`);return O}function D(O){return`"${O}"`}function z(O,H){return`${D(O)}.${D(H)}`}function S(O){return JSON.stringify(O)}function B(O){return S(O)}function U(O){if(typeof O!=="string")return O;let H=JSON.parse(O);if(typeof H!=="string")return H;try{return JSON.parse(H)}catch{return H}}function p(O){return Boolean(O&&Object.keys(O).length>0)}function y(O,H,G){if(!p(H))return"";return G.push(B(H)),` AND ${O} @> $${G.length}::text::jsonb`}function m(O){if(O.some((H)=>!Number.isFinite(H)))throw Error("Postgres vector embeddings must contain only finite numbers");return`{${O.join(",")}}`}function c(O){if(O.some((H)=>!Number.isFinite(H)))throw Error("Postgres vector embeddings must contain only finite numbers");return`[${O.join(",")}]`}function j(O){let H=null;return async()=>{if(!H)H=O().catch((G)=>{throw H=null,G});await H}}function _(O){return Error(`Postgres ${O} store is read-only in this context.`)}async function C(O,H){let G=await O.unsafe("SELECT to_regclass($1)::text AS oid",[H]);return G[0]?.oid!==null&&G[0]?.oid!==void 0}function V(O){let H=d(O.url),G=J(O.schema??g,"schema"),X=J(O.vectorTablePrefix??f,"vectorTablePrefix"),W=`${X}_vectors`,Y=S({url:H,schema:G,vectorTablePrefix:X}),Q=I.get(Y);if(Q)return Q;let Z=new b(H,{prepare:!1}),L=D(G),A=z(G,E),M=z(G,R),$=z(G,W),T=`${G}.${E}`,h=`${G}.${R}`,w=`${G}.${W}`,k=j(async()=>{await Z.unsafe(`CREATE SCHEMA IF NOT EXISTS ${L}`)}),K={sql:Z,schema:G,documentTable:A,sessionStateTable:M,vectorTable:$,hasDocumentStore:()=>C(Z,T),hasSessionStore:()=>C(Z,h),hasVectorStore:()=>C(Z,w),ensureDocumentStore:j(async()=>{await k(),await Z.unsafe(`
CREATE TABLE IF NOT EXISTS ${A} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
document JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await Z.unsafe(`
CREATE INDEX IF NOT EXISTS ${D("gm_documents_collection_idx")}
ON ${A} (collection)
`),await Z.unsafe(`
CREATE INDEX IF NOT EXISTS ${D("gm_documents_document_gin_idx")}
ON ${A} USING GIN (document)
`)}),ensureSessionStore:j(async()=>{await k(),await Z.unsafe(`
CREATE TABLE IF NOT EXISTS ${M} (
scope_key TEXT NOT NULL,
state_kind TEXT NOT NULL,
payload JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_key, state_kind)
)
`)}),ensureVectorStore:j(async()=>{await k(),await Z.unsafe("CREATE EXTENSION IF NOT EXISTS vector"),await Z.unsafe(`
CREATE TABLE IF NOT EXISTS ${$} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding DOUBLE PRECISION[] NOT NULL,
metadata JSONB NOT NULL,
content TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await Z.unsafe(`
CREATE INDEX IF NOT EXISTS ${D(`${W}_collection_idx`)}
ON ${$} (collection)
`),await Z.unsafe(`
CREATE INDEX IF NOT EXISTS ${D(`${W}_metadata_gin_idx`)}
ON ${$} USING GIN (metadata)
`)})};return I.set(Y,K),K}function P(O,H,G){return{async set(X,W){if(G?.readOnly)throw _("session");await O.ensureSessionStore(),await O.sql.unsafe(`
INSERT INTO ${O.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind)
DO UPDATE SET
payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
`,[F(X),H,B(W)])},async get(X){if(G?.readOnly&&!await O.hasSessionStore())return null;if(!G?.readOnly)await O.ensureSessionStore();let Y=(await O.sql.unsafe(`
SELECT payload::text AS payload_json
FROM ${O.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
`,[F(X),H]))[0];return Y?U(Y.payload_json):null},async deleteByScope(X){if(G?.readOnly)throw _("session");if(await O.ensureSessionStore(),X.sessionId!==void 0)return(await O.sql.unsafe(`
DELETE FROM ${O.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
RETURNING 1 AS count
`,[F(X),H])).length;return(await O.sql.unsafe(`
DELETE FROM ${O.sessionStateTable}
WHERE scope_key LIKE $1 AND state_kind = $2
RETURNING 1 AS count
`,[`${N(X)}%`,H])).length}}}function n(O,H){let G=V(O);return{async set(X,W,Y){if(H?.readOnly)throw _("document");await G.ensureDocumentStore(),await G.sql.unsafe(`
INSERT INTO ${G.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[X,W,B(Y)])},async get(X,W){if(H?.readOnly&&!await G.hasDocumentStore())return null;if(!H?.readOnly)await G.ensureDocumentStore();let Q=(await G.sql.unsafe(`
SELECT document::text AS document_json
FROM ${G.documentTable}
WHERE collection = $1 AND id = $2
`,[X,W]))[0];return Q?U(Q.document_json):null},async update(X,W,Y){if(H?.readOnly)throw _("document");if(await G.ensureDocumentStore(),(await G.sql.unsafe(`
UPDATE ${G.documentTable}
SET
document = document || $3::text::jsonb,
updated_at = NOW()
WHERE collection = $1 AND id = $2
RETURNING id
`,[X,W,B(Y)])).length===0)throw Error(`Document not found for update: ${X}/${W}`)},async query(X,W){if(H?.readOnly&&!await G.hasDocumentStore())return[];if(!H?.readOnly)await G.ensureDocumentStore();let Y=[X],Q=y("document",W,Y);return(await G.sql.unsafe(`
SELECT document::text AS document_json
FROM ${G.documentTable}
WHERE collection = $1${Q}
ORDER BY id ASC
`,Y)).map((L)=>U(L.document_json))},async queryPage(X,W){if(x(W),H?.readOnly&&!await G.hasDocumentStore())return{items:[]};if(!H?.readOnly)await G.ensureDocumentStore();let Y=[X],Q=y("document",W.filter,Y);Y.push(W.cursor??null);let Z=Y.length;Y.push(W.limit+1);let L=Y.length,A=await G.sql.unsafe(`
SELECT id, document::text AS document_json
FROM ${G.documentTable}
WHERE collection = $1${Q}
AND ($${Z}::text IS NULL OR id > $${Z})
ORDER BY id ASC
LIMIT $${L}
`,Y),M=A.slice(0,W.limit);return{items:M.map(($)=>U($.document_json)),...A.length>W.limit?{nextCursor:M.at(-1).id}:{}}},async writeBatchIfUnchanged(X){if(H?.readOnly)throw _("document");return await G.ensureDocumentStore(),G.sql.begin(async(W)=>{if((await W.unsafe(`
SELECT id
FROM ${G.documentTable}
WHERE collection = $1
AND id = $2
AND document = $3::text::jsonb
FOR UPDATE
`,[X.expected.collection,X.expected.id,B(X.expected.document)])).length===0)return!1;for(let Q of X.set)await W.unsafe(`
INSERT INTO ${G.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[Q.collection,Q.id,B(Q.document)]);return!0})},async delete(X,W){if(H?.readOnly)throw _("document");await G.ensureDocumentStore(),await G.sql.unsafe(`
DELETE FROM ${G.documentTable}
WHERE collection = $1 AND id = $2
`,[X,W])}}}function t(O,H){let G=V(O),X=P(G,"buffer",H),W=P(G,"working_memory",H),Y=P(G,"journal",H);return{saveBuffer(Q,Z){return X.set(Q,Z)},getBuffer(Q){return X.get(Q)},deleteBuffersByScope(Q){return X.deleteByScope(Q)},saveWorkingMemory(Q,Z){return W.set(Q,Z)},getWorkingMemory(Q){return W.get(Q)},deleteWorkingMemoryByScope(Q){return W.deleteByScope(Q)},saveJournal(Q,Z){return Y.set(Q,Z)},getJournal(Q){return Y.get(Q)},deleteJournalsByScope(Q){return Y.deleteByScope(Q)}}}function o(O,H){let G=V(O);return{async upsert(X,W){if(H?.readOnly)throw _("vector");await G.ensureVectorStore(),await G.sql.begin(async(Y)=>{for(let Q of W)await Y.unsafe(`
INSERT INTO ${G.vectorTable} (
collection,
id,
embedding,
metadata,
content,
updated_at
) VALUES (
$1,
$2,
$3::double precision[],
$4::text::jsonb,
$5,
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
embedding = EXCLUDED.embedding,
metadata = EXCLUDED.metadata,
content = EXCLUDED.content,
updated_at = EXCLUDED.updated_at
`,[X,Q.id,m(Q.embedding),B(Q.metadata),Q.content])})},async get(X,W){if(H?.readOnly&&!await G.hasVectorStore())return null;if(!H?.readOnly)await G.ensureVectorStore();let Q=(await G.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
0 AS score
FROM ${G.vectorTable}
WHERE collection = $1 AND id = $2
LIMIT 1
`,[X,W]))[0];if(!Q)return null;return{id:Q.id,embedding:U(Q.embedding_json),metadata:U(Q.metadata_json),content:Q.content}},async search(X,W,Y){if(Y.topK<=0||W.length===0)return[];if(H?.readOnly&&!await G.hasVectorStore())return[];if(!H?.readOnly)await G.ensureVectorStore();let Q=[X],Z=y("metadata",Y.filter,Q);Q.push(c(W));let L=Q.length;Q.push(Y.topK);let A=Q.length;return(await G.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
((embedding::vector <#> $${L}::vector) * -1) AS score
FROM ${G.vectorTable}
WHERE collection = $1${Z}
ORDER BY embedding::vector <#> $${L}::vector ASC, id ASC
LIMIT $${A}
`,Q)).map(($)=>({id:$.id,embedding:U($.embedding_json),metadata:U($.metadata_json),content:$.content,score:Number($.score)}))},async delete(X,W){if(H?.readOnly)throw _("vector");await G.ensureVectorStore(),await G.sql.unsafe(`
DELETE FROM ${G.vectorTable}
WHERE collection = $1 AND id = $2
`,[X,W])}}}async function q(O){let G=await V(O).sql.unsafe(`
SELECT
EXISTS (
SELECT 1
FROM pg_extension
WHERE extname = 'vector'
) AS installed,
EXISTS (
SELECT 1
FROM pg_available_extensions
WHERE name = 'vector'
) AS available
`);if(G[0]?.installed)return"installed";if(G[0]?.available)return"available";return"missing"}async function l(O){let H=V(O);await H.ensureDocumentStore(),await H.ensureSessionStore(),await H.ensureVectorStore()}async function a(O){let H=V(O),[G,X,W]=await Promise.all([H.hasDocumentStore(),H.hasSessionStore(),H.hasVectorStore()]);return G&&X&&W}async function i(O,H){let G=H?.getVectorExtensionStatus??q,X=H?.hasExistingStorageBackend??a,W=await G(O);if(W==="missing")return"unusable";if(W!=="installed")return"inconclusive";return await X(O)?"readable":"inconclusive"}async function e(O,H){let G=H?.getVectorExtensionStatus??q,X=H?.ensureStorageBackend??l;if(await G(O)==="missing")return!1;return await X(O),!0}export{i as probeReadOnlyPostgresStorageBackend,q as getPostgresVectorExtensionStatus,l as ensurePostgresStorageBackend,o as createPostgresVectorStore,t as createPostgresSessionStore,n as createPostgresDocumentStore,e as canBootstrapPostgresStorageBackend};
export{n as hb,t as ib,o as jb,i as kb,e as lb};
import{wb as V}from"./chunk-cw5s45qm.js";import{xb as U}from"./chunk-w0h24t3p.js";import{zb as R}from"./chunk-xmaks7z1.js";var E=R((M,Q)=>{var{defineProperty:K,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(q,v)=>{for(var z in v)K(q,z,{get:v[z],enumerable:!0})},$=(q,v,z,F)=>{if(v&&typeof v==="object"||typeof v==="function"){for(let G of X(v))if(!Y.call(q,G)&&G!==z)K(q,G,{get:()=>v[G],enumerable:!(F=W(v,G))||F.enumerable})}return q},A=(q)=>$(K({},"__esModule",{value:!0}),q),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var H=U(),B=V();async function D(){let{projectId:q,teamId:v}=(0,B.findProjectInfo)(),z=(0,B.loadToken)(q);if(!z||(0,B.isExpired)((0,B.getTokenPayload)(z.token))){let F=await(0,B.getVercelCliToken)();if(!F)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!q)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(z=await(0,B.getVercelOidcToken)(F,q,v),!z)throw new H.VercelOidcTokenError("Failed to refresh OIDC token");(0,B.saveToken)(z,q)}process.env.VERCEL_OIDC_TOKEN=z.token;return}});export default E();

Sorry, the diff of this file is too big to display

import{qb as m,rb as q$,tb as z$,ub as x,vb as _$}from"./chunk-ve2dyh5j.js";import{Ab as T$}from"./chunk-xmaks7z1.js";import{Database as D$}from"bun:sqlite";import{Buffer as l$}from"node:buffer";import{mkdirSync as c$}from"node:fs";import{dirname as d$}from"node:path";import{spawnSync as w$}from"node:child_process";import{existsSync as g$}from"node:fs";var d={};T$(d,{loadVss:()=>j$,loadVector:()=>J$,load:()=>S$,getVssLoadablePath:()=>H$,getVectorLoadablePath:()=>B$});import{join as R$}from"node:path";import{fileURLToPath as f$}from"node:url";import{arch as c,platform as v}from"node:process";import{statSync as y$}from"node:fs";var W$=[["darwin","x64"],["darwin","arm64"],["linux","x64"]];function L$($,G){return W$.find(([X,H])=>$==X&&G===H)!==null}function N$($){if($==="win32")return"dll";if($==="darwin")return"dylib";return"so"}function x$($,G){return`sqlite-vss-${$==="win32"?"windows":$}-${G}`}function Y$($){if(!L$(v,c))throw Error(`Unsupported platform for sqlite-vss, on a ${v}-${c} machine, but not in supported platforms (${W$.map(([H,Y])=>`${H}-${Y}`).join(",")}). Consult the sqlite-vss NPM package README for details. `);let G=x$(v,c),X=R$(f$(new URL(".",import.meta.url)),"..","..",G,"lib",`${$}.${N$(v)}`);if(!y$(X,{throwIfNoEntry:!1}))throw Error(`Loadble extension for sqlite-vss not found. Was the ${G} package installed? Avoid using the --no-optional flag, as the optional dependencies for sqlite-vss are required.`);return X}function B$(){return Y$("vector0")}function H$(){return Y$("vss0")}function J$($){$.loadExtension(B$())}function j$($){$.loadExtension(H$())}function S$($){J$($),j$($)}var i="vss_inner_product",h$=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/usr/lib/x86_64-linux-gnu/libsqlite3.so","/usr/lib/aarch64-linux-gnu/libsqlite3.so","/usr/lib64/libsqlite3.so","/usr/lib/libsqlite3.so"],v$=`
import { Database } from "bun:sqlite";
const [customLibraryPath, vectorPath, vssPath] = process.argv.slice(1);
if (!customLibraryPath || !vectorPath || !vssPath) {
throw new Error("Missing sqlite-vss probe paths.");
}
Database.setCustomSQLite(customLibraryPath);
const database = new Database(":memory:", { strict: true });
try {
database.loadExtension(vectorPath);
database.loadExtension(vssPath);
database.query("select vss_version() as version").get();
database.exec(
"CREATE VIRTUAL TABLE __goodmemory_vss_probe USING vss0(embedding(3)); DROP TABLE __goodmemory_vss_probe;",
);
} finally {
database.close();
}
`;function R($){if(!$)return;let G=$.trim();return G.length>0?G:void 0}function b$($){let G=R($);if(!G)return[];return G.split(",").map((X)=>X.trim()).filter((X)=>X.length>0)}function m$($){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION: ${$}. Expected a valid SQLite function identifier.`);return $}function p$($){let G=R($);if(!G)return;if(G==="off"||G==="prefer"||G==="require")return G;throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_MODE: ${G}. Expected off|prefer|require.`)}function s($){let{backend:G,customLibraryPath:X,entryPoint:H,mode:Y,path:A,paths:Z,searchFunction:j}=$;return{customLibraryPath:X,vectorExtension:{backend:G,entryPoint:H,mode:Y,path:A,paths:Z,searchFunction:j}}}function K$($){return{config:s({backend:"none",customLibraryPath:$.customLibraryPath,entryPoint:void 0,mode:"off",path:void 0,paths:[],searchFunction:$.searchFunction}),diagnostics:{available:$.source==="disabled",backend:"none",effectiveMode:"off",reason:$.reason,requestedMode:$.requestedMode,source:$.source}}}function u$($){let G=w$(process.execPath,["-e",v$,"--",$.customLibraryPath,...$.paths],{encoding:"utf8",timeout:1e4});if(G.error)return{loadable:!1,reason:G.error.message};if(G.status!==0)return{loadable:!1,reason:`${G.stdout}${G.stderr}`.trim()||`sqlite-vss probe exited with status ${G.status}`};return{loadable:!0}}function r$($={}){let G=$.exists??g$,X=($.libraryCandidatePaths??h$).find((H)=>G(H));if(!X)return{runtime:null};try{let H=d,Y=Object.hasOwn($,"getVectorLoadablePath")?$.getVectorLoadablePath:H.getVectorLoadablePath,A=Object.hasOwn($,"getVssLoadablePath")?$.getVssLoadablePath:H.getVssLoadablePath;if(!Y||!A)return{runtime:null};let Z=Y(),j=A();if(!G(Z)||!G(j))return{runtime:null};let F={customLibraryPath:X,paths:[Z,j]},_=($.probeRuntime??u$)(F);if(!_.loadable)return{runtime:null,unavailableReason:_.reason??"Bundled sqlite-vss runtime probe failed."};return{runtime:F}}catch(H){return{runtime:null,unavailableReason:`Failed to inspect bundled sqlite-vss runtime: ${H instanceof Error?H.message:String(H)}`}}}function O$($=process.env,G){let X=R($.GOODMEMORY_SQLITE_CUSTOM_LIBRARY_PATH),H=R($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),Y=b$($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),A=p$($.GOODMEMORY_SQLITE_VECTOR_MODE),Z=m$(R($.GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION)??i),j=R($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_ENTRYPOINT),F=G?.inspectBundledSQLiteVssRuntime?G.inspectBundledSQLiteVssRuntime():G?.detectBundledSQLiteVssRuntime?{runtime:G.detectBundledSQLiteVssRuntime()}:r$(),_=F.runtime,O=F.unavailableReason,W=A??(Y.length>0||_||O?"prefer":"off");if(W==="off")return K$({customLibraryPath:X,requestedMode:W,searchFunction:Z,source:"disabled"});if(Y.length>0)return{config:s({backend:"sql-function",customLibraryPath:X,entryPoint:j,mode:W,path:H,paths:Y,searchFunction:Z}),diagnostics:{available:!0,backend:"sql-function",effectiveMode:W,requestedMode:W,source:"env"}};if(_){let U=W==="require"?"require":"prefer";return{config:s({backend:"sqlite-vss",customLibraryPath:X??_.customLibraryPath,entryPoint:j,mode:U,path:_.paths.join(","),paths:_.paths,searchFunction:Z}),diagnostics:{available:!0,backend:"sqlite-vss",effectiveMode:U,requestedMode:W,source:"bundled-sqlite-vss"}}}return K$({customLibraryPath:X,requestedMode:W,searchFunction:Z,source:"unavailable",reason:O??"SQLite vector acceleration was requested, but no supported sqlite-vss runtime assets were detected and no manual GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH was configured."})}function U$($,G){if(!$.customLibraryPath)return;G.setCustomSQLite($.customLibraryPath)}function k$($,G){if($.mode==="off"||!($.paths?.length??0))return{loaded:!1,reason:"SQLite vector acceleration is disabled."};try{for(let X of $.paths)G.loadExtension(X,$.entryPoint);return{loaded:!0}}catch(X){let H=X instanceof Error?X.message:String(X);if($.mode==="prefer")return{loaded:!1,reason:`Failed to load SQLite vector extension at ${$.path}: ${H}`};throw Error(`Failed to load SQLite vector extension at ${$.path}: ${H}`)}}var b=null,o=null;function s$(){if(!b)b={customLibraryPath:Q$().config.customLibraryPath},U$(b,D$);return b}function Q$(){if(!o)o=O$();return o}function i$($,G){if(G?.readOnly||$===":memory:")return;c$(d$($),{recursive:!0})}function n($,G){return s$(),i$($,G),new D$($,{create:G?.readOnly?!1:!0,readonly:G?.readOnly??!1,strict:!0})}function o$($){$.exec(`
CREATE TABLE IF NOT EXISTS documents (
collection TEXT NOT NULL,
id TEXT NOT NULL,
json TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
`)}function a$($){$.exec(`
CREATE TABLE IF NOT EXISTS session_buffers (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_working_memory (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_journals (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`)}function n$($){$.exec(`
CREATE TABLE IF NOT EXISTS vectors (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding_json TEXT NOT NULL,
metadata_json TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE TABLE IF NOT EXISTS vector_index_state (
table_name TEXT PRIMARY KEY,
collection TEXT NOT NULL,
dimension INTEGER NOT NULL,
dirty INTEGER NOT NULL
);
`)}function D($){return JSON.parse($)}function L($,G){let X=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(G);return X!==null&&X!==void 0}function S($){return Error(`SQLite ${$} store is read-only in this context.`)}function t$($,G){let X=Math.min($.length,G.length),H=0;for(let Y=0;Y<X;Y+=1)H+=$[Y]*G[Y];return H}function e$($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function A$($){let{alias:G,keyParameterIndex:X,value:H,valueParameterIndex:Y}=$,A=`EXISTS (
SELECT 1
FROM json_each(metadata_json) AS ${G}
WHERE ${G}.key = ?${X}`;if(H===null)return`${A}
AND ${G}.type = 'null'
)`;if(typeof H==="boolean")return`${A}
AND ${G}.type = '${H?"true":"false"}'
)`;if(typeof H==="number")return`${A}
AND ${G}.type IN ('integer', 'real')
AND ${G}.atom = ?${Y}
)`;return`${A}
AND ${G}.type = 'text'
AND ${G}.atom = ?${Y}
)`}function N($){return`"${$.replaceAll('"','""')}"`}function $4($){if(/^[A-Za-z0-9]+$/.test($))return $;return`x_${l$.from($,"utf8").toString("hex")}`}function F$($,G){return`vss_vectors_${$4($)}_dim_${G}`}function p($,G,X){$.query(`DELETE FROM ${N(G)} WHERE rowid = ?1`).run(X)}function M$($){let{database:G,embeddingJson:X,rowid:H,tableName:Y}=$;p(G,Y,H),G.query(`INSERT INTO ${N(Y)} (rowid, embedding)
VALUES (?1, json(?2))`).run(H,X)}function G4($){let{collection:G,config:X,database:H,filter:Y,queryEmbedding:A,topK:Z}=$;if(X.mode==="off"||!X.paths?.length)return null;let j=[G,JSON.stringify(A)],F=[];if(Y)for(let[W,U]of Object.entries(Y)){if(!e$(U))return null;j.push(W);let Q=j.length,C=`metadata_filter_${F.length+1}`;if(U===null||typeof U==="boolean"){F.push(A$({alias:C,keyParameterIndex:Q,value:U}));continue}j.push(U),F.push(A$({alias:C,keyParameterIndex:Q,value:U,valueParameterIndex:j.length}))}j.push(Z);let _=["collection = ?1",...F];return H.query(`SELECT
id,
embedding_json,
metadata_json,
content,
${X.searchFunction||i}(embedding_json, ?2) AS score
FROM vectors
WHERE ${_.join(" AND ")}
ORDER BY score DESC, id ASC
LIMIT ?${j.length}`).all(...j).map((W)=>({id:W.id,embedding:D(W.embedding_json),metadata:D(W.metadata_json),content:W.content,score:Number(W.score)}))}function M4($,G){let X=n($,G);if(!G?.readOnly)o$(X);let H=X.query(`INSERT INTO documents (collection, id, json)
VALUES (?1, ?2, ?3)
ON CONFLICT(collection, id) DO UPDATE SET json = excluded.json`),Y=X.query("SELECT json FROM documents WHERE collection = ?1 AND id = ?2"),A=X.query("SELECT json FROM documents WHERE collection = ?1"),Z=X.query(`SELECT id, json
FROM documents
WHERE collection = ?1 AND (?2 IS NULL OR id > ?2)
ORDER BY id ASC
LIMIT ?3`),j=X.query("DELETE FROM documents WHERE collection = ?1 AND id = ?2");function F(O){let W=O instanceof Error?O.message:String(O);return/SQLITE_BUSY|SQLITE_LOCKED|database is locked|database is busy/i.test(W)}function _(O){try{X.exec("BEGIN IMMEDIATE")}catch(W){if(F(W))return!1;throw W}try{let W=Y.get(O.expected.collection,O.expected.id);if(!W||W.json!==JSON.stringify(O.expected.document))return X.exec("ROLLBACK"),!1;for(let U of O.set)H.run(U.collection,U.id,JSON.stringify(U.document));return X.exec("COMMIT"),!0}catch(W){try{X.exec("ROLLBACK")}catch{}if(F(W))return!1;throw W}}return{async set(O,W,U){H.run(O,W,JSON.stringify(U))},async get(O,W){let U=Y.get(O,W);return U?D(U.json):null},async update(O,W,U){let Q=await this.get(O,W);if(!Q)throw Error(`Document not found for update: ${O}/${W}`);await this.set(O,W,_$(Q,U))},async query(O,W){return A.all(O).map((Q)=>D(Q.json)).filter((Q)=>x(Q,W))},async queryPage(O,W){z$(W);let U=[],Q=Math.max(64,W.limit+1),C=W.cursor??null;while(U.length<=W.limit){let V=Z.all(O,C,Q);if(V.length===0)break;for(let u of V){let f=D(u.json);if(x(f,W.filter)){if(U.push({document:f,id:u.id}),U.length>W.limit)break}}if(C=V.at(-1).id,V.length<Q)break}let w=U.slice(0,W.limit);return{items:w.map(({document:V})=>V),...U.length>W.limit?{nextCursor:w.at(-1).id}:{}}},async writeBatchIfUnchanged(O){if(G?.readOnly)throw S("document");return _(O)},async delete(O,W){j.run(O,W)}}}function a($,G,X){if(X?.readOnly&&!L($,G))return{async set(){throw S("session")},async get(){return null},async deleteByScope(){throw S("session")}};let H=$.query(`INSERT INTO ${G} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO UPDATE SET json = excluded.json`),Y=$.query(`SELECT json FROM ${G} WHERE scope_key = ?1`),A=$.query(`DELETE FROM ${G} WHERE scope_key = ?1`),Z=$.query(`DELETE FROM ${G} WHERE scope_key LIKE ?1`);return{async set(j,F){H.run(m(j),JSON.stringify(F))},async get(j){let F=Y.get(m(j));return F?D(F.json):null},async deleteByScope(j){if(j.sessionId!==void 0){let _=A.run(m(j));return Number(_.changes??0)}let F=Z.run(`${q$(j)}%`);return Number(F.changes??0)}}}function q4($,G){let X=n($,G);if(!G?.readOnly)a$(X);let H=a(X,"session_buffers",G),Y=a(X,"session_working_memory",G),A=a(X,"session_journals",G);return{saveBuffer(Z,j){return H.set(Z,j)},getBuffer(Z){return H.get(Z)},deleteBuffersByScope(Z){return H.deleteByScope(Z)},saveWorkingMemory(Z,j){return Y.set(Z,j)},getWorkingMemory(Z){return Y.get(Z)},deleteWorkingMemoryByScope(Z){return Y.deleteByScope(Z)},saveJournal(Z,j){return A.set(Z,j)},getJournal(Z){return A.get(Z)},deleteJournalsByScope(Z){return A.deleteByScope(Z)}}}function z4($,G,X){let H=X?.runtimeResolution??Q$(),Y=X?.vectorExtensionConfig??H.config.vectorExtension,A=X?.runtimeResolution?.diagnostics??H.diagnostics,Z=n($,G);if(!G?.readOnly)n$(Z);if(A.requestedMode==="require"&&!A.available)throw Error(A.reason??"SQLite vector acceleration is required but no supported runtime is available.");let j=!G?.readOnly||L(Z,"vectors"),F=new Set,_=null,O=G?.readOnly?null:Z.query(`INSERT INTO vectors (
collection,
id,
embedding_json,
metadata_json,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(collection, id) DO UPDATE SET
embedding_json = excluded.embedding_json,
metadata_json = excluded.metadata_json,
content = excluded.content`),W=j?Z.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,U=j?Z.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,Q=j?Z.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,C=j?Z.query(`SELECT rowid, embedding_json
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,w=j?Z.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND rowid = ?2`):null,V=G?.readOnly?null:Z.query("DELETE FROM vectors WHERE collection = ?1 AND id = ?2"),f=!G?.readOnly||L(Z,"vector_index_state")?Z.query(`SELECT dirty
FROM vector_index_state
WHERE table_name = ?1`):null,P$=G?.readOnly?null:Z.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 1)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 1`),C$=G?.readOnly?null:Z.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 0)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 0`);function t(){if(_)return _;let B=(X?.loadVectorExtension??k$)(Y,Z);return _=B&&typeof B==="object"&&"loaded"in B?B:{loaded:Y.mode!=="off"&&Boolean(Y.paths?.length)},_}function r(){return Y.backend==="sqlite-vss"&&t().loaded}function l(B,k){let J=F$(B,k);P$.run(J,B,k)}function V$(B){C$.run(B.tableName,B.collection,B.dimension)}function e(B){if(!B.existed)return!0;let k=f.get(B.tableName);return!k||k.dirty!==0}function $$(B){return f?.get(B)?.dirty===0}function G$(B,k,J){let K=Q.all(B).filter((z)=>{return D(z.embedding_json).length===k}),M=new Set(K.map((z)=>z.rowid)),q=Z.query(`SELECT rowid FROM ${N(J)}`).all();for(let z of q)if(!M.has(z.rowid))p(Z,J,z.rowid);for(let z of K)M$({database:Z,embeddingJson:z.embedding_json,rowid:z.rowid,tableName:J});V$({collection:B,dimension:k,tableName:J})}function g(B,k){if(!r())return null;let J=F$(B,k);if(F.has(J)){if(G?.readOnly){if(!$$(J))return F.delete(J),null;return J}if(e({existed:!0,tableName:J}))G$(B,k,J);return J}if(G?.readOnly){if(!L(Z,J))return null;if(!$$(J))return null;return F.add(J),J}let K=L(Z,J);if(Z.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${N(J)}
USING vss0(embedding(${k}))`),e({existed:K,tableName:J}))G$(B,k,J);return F.add(J),J}function E$(B){let{collection:k,filter:J,queryEmbedding:K,topK:M}=B,q=K.length,z=g(k,q);if(!z)return null;let P=U.all(k).filter((T)=>{return D(T.embedding_json).length===q}).length;if(P===0)return[];let h=JSON.stringify(K),E=Math.min(P,Math.max(M,J?M*4:M));while(E>0){let T=Z.query(`SELECT rowid, distance
FROM ${N(z)}
WHERE vss_search(embedding, vss_search_params(json(?1), ?2))`).all(h,E),I=[];for(let X$ of T){let y=w.get(k,X$.rowid);if(!y)continue;let I$=D(y.embedding_json),Z$=D(y.metadata_json);if(!x(Z$,J))continue;I.push({id:y.id,embedding:I$,metadata:Z$,content:y.content,score:1/(1+Number(X$.distance))})}if(!J||I.length>=M||E>=P)return I.slice(0,M);E=Math.min(P,E*2)}return[]}return{async upsert(B,k){if(G?.readOnly)throw S("vector");Z.transaction((K)=>{let M=r();for(let q of K){let z=C.get(B,q.id),P=z?D(z.embedding_json).length:null,h=JSON.stringify(q.embedding);if(O.run(B,q.id,h,JSON.stringify(q.metadata),q.content),!M){if(z&&P!==null&&P!==q.embedding.length)l(B,P);l(B,q.embedding.length);continue}let E=C.get(B,q.id);if(!E)continue;if(z&&P!==null&&P!==q.embedding.length){let I=g(B,P);if(I)p(Z,I,z.rowid)}let T=g(B,q.embedding.length);if(!T)continue;M$({database:Z,embeddingJson:h,rowid:E.rowid,tableName:T})}})(k)},async get(B,k){if(!j)return null;let J=W.get(B,k);if(!J)return null;return{id:J.id,embedding:D(J.embedding_json),metadata:D(J.metadata_json),content:J.content}},async search(B,k,J){if(J.topK<=0||k.length===0)return[];if(!j)return[];if(Y.mode!=="off"&&Y.paths?.length&&t().loaded)try{let K=Y.backend==="sqlite-vss"?E$({collection:B,filter:J.filter,queryEmbedding:k,topK:J.topK}):(X?.runExtensionSearch??G4)({collection:B,config:Y,database:Z,filter:J.filter,queryEmbedding:k,topK:J.topK});if(K!==null)return K;if(Y.mode==="require")throw Error("SQLite vector extension search could not satisfy the current query without durable fallback.")}catch(K){if(Y.mode==="require"){let M=K instanceof Error?K.message:String(K);throw Error(`Failed to execute SQLite vector extension search for ${B}: ${M}`)}}return U.all(B).map((K)=>{let M=D(K.embedding_json),q=D(K.metadata_json);return{id:K.id,embedding:M,metadata:q,content:K.content,score:t$(M,k)}}).filter((K)=>x(K.metadata,J.filter)).sort((K,M)=>{if(M.score!==K.score)return M.score-K.score;return K.id.localeCompare(M.id)}).slice(0,J.topK)},async delete(B,k){if(G?.readOnly)throw S("vector");Z.transaction(()=>{let K=C.get(B,k),M=r();if(K&&M){let q=D(K.embedding_json).length,z=g(B,q);if(z)p(Z,z,K.rowid)}if(K&&!M){let q=D(K.embedding_json).length;l(B,q)}V.run(B,k)})()}}}export{z4 as createSQLiteVectorStore,q4 as createSQLiteSessionStore,M4 as createSQLiteDocumentStore};
export{M4 as mb,q4 as nb,z4 as ob};
import{xb as D}from"./chunk-w0h24t3p.js";import{Bb as K,zb as q}from"./chunk-xmaks7z1.js";var S=q((kz,O)=>{var{create:m,defineProperty:v,getOwnPropertyDescriptor:_,getOwnPropertyNames:a,getPrototypeOf:n}=Object,r=Object.prototype.hasOwnProperty,t=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},I=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of a(B))if(!r.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=_(B,G))||H.enumerable})}return z},V=(z,B,F)=>(F=z!=null?m(n(z)):{},I(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),e=(z)=>I(v({},"__esModule",{value:!0}),z),M={};t(M,{findRootDir:()=>Bz,getUserDataDir:()=>Fz});O.exports=e(M);var Y=V(K("path")),o=V(K("fs")),J=V(K("os")),zz=D();function Bz(){try{let z=process.cwd();while(z!==Y.default.dirname(z)){let B=Y.default.join(z,".vercel");if(o.default.existsSync(B))return z;z=Y.default.dirname(z)}}catch(z){throw new zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Fz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(J.default.platform()){case"darwin":return Y.default.join(J.default.homedir(),"Library/Application Support");case"linux":return Y.default.join(J.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var u=q((fz,l)=>{var{create:Gz,defineProperty:b,getOwnPropertyDescriptor:Hz,getOwnPropertyNames:Kz,getPrototypeOf:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},j=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Kz(B))if(!Wz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=Hz(B,G))||H.enumerable})}return z},E=(z,B,F)=>(F=z!=null?Gz(Qz(z)):{},j(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Yz=(z)=>j(b({},"__esModule",{value:!0}),z),x={};Xz(x,{isValidAccessToken:()=>vz,readAuthConfig:()=>$z,writeAuthConfig:()=>qz});l.exports=Yz(x);var Z=E(K("fs")),y=E(K("path")),Zz=P();function C(){let z=(0,Zz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return y.join(z,"auth.json")}function $z(){try{let z=C();if(!Z.existsSync(z))return null;let B=Z.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function qz(z){let B=C(),F=y.dirname(B);if(!Z.existsSync(F))Z.mkdirSync(F,{mode:504,recursive:!0});Z.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function vz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var k=q((iz,g)=>{var{defineProperty:R,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz}=Object,Lz=Object.prototype.hasOwnProperty,Jz=(z,B)=>{for(var F in B)R(z,F,{get:B[F],enumerable:!0})},Vz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Lz.call(z,G)&&G!==F)R(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},Az=(z)=>Vz(R({},"__esModule",{value:!0}),z),c={};Jz(c,{processTokenResponse:()=>Dz,refreshTokenRequest:()=>Tz});g.exports=Az(c);var A=K("os"),Nz="https://vercel.com",Rz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",h=`@vercel/oidc node-${process.version} ${(0,A.platform)()} (${(0,A.arch)()}) ${(0,A.hostname)()}`,N=null;async function wz(){if(N)return N;let z=`${Nz}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":h}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return N=H,H}async function Tz(z){let B=await wz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":h},body:new URLSearchParams({client_id:Rz,grant_type:"refresh_token",...z})})}async function Dz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var P=q((dz,s)=>{var{create:Iz,defineProperty:U,getOwnPropertyDescriptor:Mz,getOwnPropertyNames:Oz,getPrototypeOf:Sz}=Object,jz=Object.prototype.hasOwnProperty,Ez=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},i=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Oz(B))if(!jz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=Mz(B,G))||H.enumerable})}return z},d=(z,B,F)=>(F=z!=null?Iz(Sz(z)):{},i(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),xz=(z)=>i(U({},"__esModule",{value:!0}),z),p={};Ez(p,{assertVercelOidcTokenResponse:()=>w,findProjectInfo:()=>uz,getTokenPayload:()=>hz,getVercelCliToken:()=>Cz,getVercelDataDir:()=>yz,getVercelOidcToken:()=>lz,isExpired:()=>gz,loadToken:()=>cz,saveToken:()=>Pz});s.exports=xz(p);var $=d(K("path")),Q=d(K("fs")),X=D(),L=S(),W=u(),f=k();function yz(){let B=(0,L.getUserDataDir)();if(!B)return null;return $.join(B,"com.vercel.cli")}async function Cz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,f.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,f.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function lz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return w(T),T}function w(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function uz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=$.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function Pz(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=$.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync($.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function cz(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=$.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return w(H),H}function hz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function gz(z){return z.exp*1000<Date.now()}});export default P();
export{P as wb};
import{readFileSync as W}from"node:fs";var X=new URL("../../package.json",import.meta.url),I;function Y(){if(I)return I;let x=JSON.parse(W(X,"utf8"));if(typeof x.version!=="string"||x.version.length===0)throw Error("Unable to read GoodMemory package version.");return I=x.version,I}var q="https://github.com/hjqcan/GoodMemory",Q="https://goodmemory.vibenest.net";function $(x={}){let z=x.version??Y();return{schemaVersion:"goodmemory.capability/v2",name:"goodmemory",version:z,kind:"memory-layer",summary:"Durable user/project memory layer for chat apps, copilots, and coding agents.",description:"GoodMemory is the product memory layer between an app or installed agent host and the model runtime: write selected facts, recall the right context, inject it into the next turn, audit what happened, and delete it when it is wrong.",notA:["llm","agent-framework","vector-database","rag-system"],license:"MIT",homepage:`${q}#readme`,repository:q,documentation:{inspector:`${q}/blob/main/docs/GoodMemory-Inspector-and-Admin-API.md`,llmsTxt:`${q}/blob/main/llms.txt`,readme:`${q}#readme`,quickstart:`${q}#quickstart-codex-or-claude-code-memory`},install:{npmGlobal:`npm install -g goodmemory@${z}`,npmPackage:`npm install goodmemory@${z}`,bun:`bun add goodmemory@${z}`},memoryApi:["remember","recall","buildContext","feedback","forget","exportMemory","deleteAllMemory"],onboarding:[{audience:"installed-coding-agent-host",when:"You are, or run inside, Claude Code or Codex.",method:"cli",steps:[`npm install -g goodmemory@${z}`,"goodmemory setup","goodmemory status"],autoDetect:"goodmemory adopt",docs:`${q}#quickstart-codex-or-claude-code-memory`},{audience:"mcp-client",when:"You speak the Model Context Protocol (Cursor, Windsurf, Cline, Claude Desktop, Gemini CLI, OpenCode, or a custom MCP client).",method:"mcp",mcpServer:{command:"goodmemory-mcp",args:["--standalone","--user-id","YOUR_USER_ID"]},autoDetect:"goodmemory adopt",docs:`${q}#standalone-mcp-for-any-client`},{audience:"framework-agent-or-backend",when:"You are a framework agent (LangGraph, custom loop) or a backend that calls memory as an HTTP service.",method:"http",endpoint:Q,selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",pythonClient:"pip install goodmemory-client",docs:`${q}#pythonfastapi-http-bridge`}],mcp:{command:"goodmemory-mcp",standaloneArgs:["--standalone","--user-id","YOUR_USER_ID"],primaryTools:["goodmemory_get_context","goodmemory_remember"],readOnlyToolCount:8,writeTool:"goodmemory_remember (opt-in via --allow-write)",registryName:"io.github.hjqcan/goodmemory",docs:`${q}#standalone-mcp-for-any-client`},http:{hosted:Q,liveness:`${Q}/healthz`,wellKnown:`${Q}/.well-known/goodmemory.json`,auth:"bearer-token",selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",endpoints:{recall:"POST /memory/recall-context",remember:"POST /memory/remember",feedback:"POST /memory/feedback",export:"POST /memory/export",forget:"POST /memory/forget",revise:"POST /memory/revise"},pythonClient:"goodmemory-client (PyPI)",docs:`${q}#pythonfastapi-http-bridge`},benchmarks:{currentClaims:[{name:"LoCoMo",config:"full 10 conversations, 1540 non-adversarial questions",metric:"independent official judge protocol; strict deterministic token-F1 reported separately",result:"official 0.8708; strict 0.6299; open-domain 0.6146 (59/96)",reference:"historical no-memory 0.0045",claimDeclaration:`${q}/blob/main/benchmark-claims/locomo.json`,runtimeProfile:"recommended+provider-embedding+provider-reranking@0.6.0",measuredPackageVersion:"0.6.0"},{name:"BEAM",config:"100K, 400 questions, 1051 rubric items",metric:"independent official unified-rubric score; strict binary and paper protocol disclosed separately",result:"unified 0.7651; strict 0.620 (248/400); generalized recall 0.8276",reference:"public full-400 same-protocol reference 0.49",claimDeclaration:`${q}/blob/main/benchmark-claims/beam.json`,runtimeProfile:"goodmemory-hybrid-generalized+evidence-pack@0.6.0",measuredPackageVersion:"0.6.0"},{name:"MemoryAgentBench",config:"Conflict Resolution 73 questions; Test-Time Learning 30 questions",metric:"deterministic upstream match-mode scoring, judge-free",result:"CR 0.959; TTL 0.933",reference:"no-memory 0.000 for CR and TTL",claimDeclaration:`${q}/blob/main/benchmark-claims/memoryagentbench.json`,runtimeProfile:"recommended-evidence-pack-cr-ttl@0.6.0",measuredPackageVersion:"0.6.0"}],historicalEvidence:{url:`${q}/tree/main/benchmark-claims`,note:"LongMemEval and ImplicitMemBench remain reproducible versioned internal evidence, not current-production claims for this package version."}},capabilities:{localFirst:!0,embeddingFreeDefault:!0,durableStore:"sqlite (default), postgres (opt-in)",audit:!0,deletion:!0,localInspector:"goodmemory inspector serve (loopback-only React console and /admin/v1 API)",correctByDefaultRecall:"Recall never silently degrades: a downgraded strategy carries routing.warnings (semantic_recall_inactive) and routing.warningMessages (semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET) instead of quietly returning the lexical floor."},canonicalSources:{prose:`${q}#readme`,benchmarks:`${q}/tree/main/benchmark-claims`,note:"This runtime descriptor exposes only claims accepted for the installed package version. Versioned historical results remain in benchmark-claims/*.json."}}}
export{$ as a};
function t(o){if(o===void 0)return;let e=o.trim();return e.length>0?e:void 0}function i(o){let e=o.userId.trim();if(e.length===0)throw Error("MemoryScope requires a non-empty userId");return{userId:e,tenantId:t(o.tenantId),workspaceId:t(o.workspaceId),agentId:t(o.agentId),sessionId:t(o.sessionId)}}function n(o){let e=i(o);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId??""].join("::")}function u(o){let e=i(o);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId].map((r)=>r??"").join("::")}function m(o,e){return n(o)===n(e)}function d(o){if(!Number.isSafeInteger(o.limit)||o.limit<=0)throw Error("Document query page limit must be a positive integer.")}function p(o,e){if(!e)return!0;let r=o;return Object.entries(e).every(([c,s])=>r[c]===s)}function g(o,e){return{...o,...e}}
export{i as pb,n as qb,u as rb,m as sb,d as tb,p as ub,g as vb};
import{zb as I}from"./chunk-xmaks7z1.js";var X=I((Y,H)=>{var{defineProperty:z,getOwnPropertyDescriptor:K,getOwnPropertyNames:L}=Object,Q=Object.prototype.hasOwnProperty,R=(j,b)=>{for(var v in b)z(j,v,{get:b[v],enumerable:!0})},U=(j,b,v,B)=>{if(b&&typeof b==="object"||typeof b==="function"){for(let q of L(b))if(!Q.call(j,q)&&q!==v)z(j,q,{get:()=>b[q],enumerable:!(B=K(b,q))||B.enumerable})}return j},W=(j)=>U(z({},"__esModule",{value:!0}),j),F={};R(F,{VercelOidcTokenError:()=>G});H.exports=W(F);class G extends Error{constructor(j,b){super(j);this.name="VercelOidcTokenError",this.cause=b}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});
export{X as xb};
import{createRequire as k}from"node:module";var g=Object.create;var{getPrototypeOf:h,defineProperty:f,getOwnPropertyNames:i}=Object;var j=Object.prototype.hasOwnProperty;var l=(a,b,c)=>{c=a!=null?g(h(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of i(a))if(!j.call(d,e))f(d,e,{get:()=>a[e],enumerable:!0});return d};var m=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var n=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:(d)=>b[c]=()=>d})};var p=k(import.meta.url);
export{l as yb,m as zb,n as Ab,p as Bb};

Sorry, the diff of this file is too big to display

function QI(I){return I.lifecycle??"active"}function EE(I){return QI(I)==="active"}function ME(I,d){let E=new Date(d).getTime();if(Number.isNaN(E))return!1;for(let M of[I.validUntil,I.expiresAt]){if(M===void 0)continue;let R=new Date(M).getTime();if(!Number.isNaN(R)&&R<=E)return!0}return!1}function Q(I){let d=I?.trim().toLowerCase();return d&&d.length>0?d:"general_response"}function RE(I){return[I.kind,Q(I.appliesTo),I.normalizedRule.trim().toLowerCase()].join("\x00")}function v(I){return I?.extractedAt??new Date(0).toISOString()}function SE(I){let d=I.updatedAt??I.createdAt??new Date(0).toISOString();return{userId:I.userId,identity:I.identity??{},expertise:I.expertise??{primarySkills:[],domains:[]},activeContext:I.activeContext??{goals:[],currentProjects:[]},version:I.version??1,updatedAt:I.updatedAt??d,createdAt:I.createdAt??d}}function PE(I){return{id:I.id,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,category:I.category,value:I.value,tags:I.tags,attributes:I.attributes,confidence:I.confidence??1,source:I.source,evidenceCount:I.evidenceCount??1,isPinned:I.isPinned,supersededBy:I.supersededBy??null,lifecycle:I.lifecycle??"active",updatedAt:I.updatedAt??v(I.source)}}function OE(I){let d=I.createdAt??I.updatedAt??v(I.source);return{id:I.id,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,category:I.category,content:I.content,tags:I.tags,attributes:I.attributes,confidence:I.confidence??1,importance:I.importance??1,source:I.source,factKind:I.factKind,scopeKind:I.scopeKind,subject:I.subject,accessCount:I.accessCount??0,lastAccessedAt:I.lastAccessedAt,verificationPressureCount:I.verificationPressureCount??0,lastVerificationHintAt:I.lastVerificationHintAt,validFrom:I.validFrom,validUntil:I.validUntil,expiresAt:I.expiresAt,demotedAt:I.demotedAt,demotionReason:I.demotionReason,supersededBy:I.supersededBy??null,lifecycle:I.lifecycle??"active",isActive:I.isActive??!0,embeddingId:I.embeddingId,createdAt:I.createdAt??d,updatedAt:I.updatedAt??d}}function kE(I){let d=I.createdAt??I.updatedAt??v(I.source);return{id:I.id,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,title:I.title,pointer:I.pointer,description:I.description,confidence:I.confidence??1,source:I.source,referenceKind:I.referenceKind,subject:I.subject,tags:I.tags,attributes:I.attributes,supersededBy:I.supersededBy??null,lifecycle:I.lifecycle??"active",createdAt:I.createdAt??d,updatedAt:I.updatedAt??d}}function xE(I){return{id:I.id,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,summary:I.summary,keyDecisions:I.keyDecisions??[],unresolvedItems:I.unresolvedItems??[],topics:I.topics??[],entities:I.entities,emotionalTone:I.emotionalTone,importance:I.importance??1,confidence:I.confidence??1,locale:I.locale,embeddingId:I.embeddingId,createdAt:I.createdAt??new Date(0).toISOString(),archivedAt:I.archivedAt}}function _E(I){return{id:I.id,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,rule:I.rule,kind:I.kind,appliesTo:I.appliesTo,why:I.why,evidence:I.evidence??[],tags:I.tags,attributes:I.attributes,confidence:I.confidence??1,source:I.source,supersededBy:I.supersededBy??null,lifecycle:I.lifecycle??"active",lastUsedAt:I.lastUsedAt,updatedAt:I.updatedAt??v(I.source)}}function CE(I){let d=I.createdAt??I.lastActiveAt??new Date(0).toISOString();return{sessionId:I.sessionId,userId:I.userId,messages:I.messages??[],summary:I.summary??null,summaryUpToIndex:I.summaryUpToIndex??0,createdAt:I.createdAt??d,lastActiveAt:I.lastActiveAt??d}}function LE(I){return{sessionId:I.sessionId,userId:I.userId,currentGoal:I.currentGoal,constraints:I.constraints,openLoops:I.openLoops??[],temporaryDecisions:I.temporaryDecisions,toolState:I.toolState,state:I.state,updatedAt:I.updatedAt??new Date(0).toISOString()}}function GE(I){return{sessionId:I.sessionId,userId:I.userId,title:I.title,currentState:I.currentState,taskSpecification:I.taskSpecification,filesAndFunctions:I.filesAndFunctions??[],workflow:I.workflow??[],errorsAndCorrections:I.errorsAndCorrections??[],systemDocumentation:I.systemDocumentation??[],learnings:I.learnings??[],keyResults:I.keyResults??[],worklog:I.worklog??[],lastSummarizedMessageId:I.lastSummarizedMessageId,updatedAt:I.updatedAt??new Date(0).toISOString()}}function sE(I){return{...I}}var cI={active:["active","superseded","inactive"],superseded:["superseded","inactive"],inactive:["inactive","active"]};function DE(I,d){if(!cI[I].includes(d))throw Error(`Invalid lifecycle transition: ${I} -> ${d}`);return d}var VI=Symbol.for("goodmemory.authorizedRecallAgentScope");function jE(I,d){return{...I,memoryType:d}}function HE(I,d){if(I.tenantId===void 0&&d.tenantId!==void 0)return!1;if(I.workspaceId===void 0&&d.workspaceId!==void 0)return!1;if(I.agentId===void 0&&d.agentId!==void 0)return!1;return!0}function NE(I,d){if(d.agentId===I.agentId)return!0;return I.agentId!==void 0&&d[VI]===I.agentId}function f(I){if(I.enactmentSurface!=="text_response")return!1;return Boolean(I.applicability.textResponsePlan||I.applicability.computedResponseRule||I.applicability.urlTemplate||I.applicability.pathTemplate||I.applicability.guard||I.applicability.guardedBehavior||(I.applicability.replacementPairs?.length??0)>0||(I.applicability.forbiddenFragments?.length??0)>0||(I.applicability.preferredAlternatives?.length??0)>0||(I.applicability.preferredFragments?.length??0)>0||(I.applicability.exactFragments?.prefixes?.length??0)>0||(I.applicability.exactFragments?.required?.length??0)>0||(I.applicability.exactFragments?.suffixes?.length??0)>0)}function BI(I){if(I.enactmentSurface!=="host_action")return!1;return Boolean(I.applicability.canonicalFirstAction||(I.applicability.argumentOrder?.length??0)>0)}var OI="goodmemory.behavioral_policy",kI="goodmemory.behavioral_policy.steering_only",bI="goodmemory.behavioral_policy.version",mI=2,FI=["always","for any","in this environment","must","should","whenever","when using"],zI=["closing","end with","opening","prefix","sign off","signature","start with","subject line","suffix"],fI=["argument","command","first action","parameter","query language","tool"],hI=["avoid","don't","do not","must not","never","rather than","instead of"],oI=[/\bwhen\s+(.+?)(?:[,.]|$)/iu,/\bif\s+(.+?)(?:[,.]|$)/iu,/\bbefore\s+(.+?)(?:[,.]|$)/iu,/\bfor\s+(.+?)(?:[,.]|$)/iu,/\bon\s+(.+?)\s+requests?(?:[,.]|$)/iu],vI=[/\b([a-z_][a-z0-9_]*\([^)]*\))\b/u,/\b(?:command|tool|action|utility)\s+([A-Za-z_][A-Za-z0-9_]*)\b/iu,/\buse\s+([A-Z][A-Za-z0-9_]*|[a-z_]+_[a-z0-9_]*)\s+(?:first|instead|before|for this)\b/iu,/\boutput\s+(?:the exact\s+)?([A-Za-z_][A-Za-z0-9_]*)\b/iu,/\b([A-Z][A-Za-z0-9_]*|[a-z_]+_[a-z0-9_]*)(?=\s+(?:takes|path|file|first|second|third|before|instead))/u],p=new Set(["a","an","before","exact","for","if","the","when"]),n={from:"http://",to:"https://"},wI="<page>",u=/\.[A-Za-z0-9]{2,8}/u,II=/[A-Za-z0-9_-]+\.[A-Za-z0-9]{2,8}|\.[A-Za-z0-9]{2,8}/u,xI={first_action:8,syntax_constraint:7,guarded_policy:6,format_contract:5,avoidance:4,preference:3,transformation_rule:2,exemplar_fact:1},_I={example_only:3,pattern_bounded:2,general:1};function s(I){return I?.trim().toLowerCase()??""}function D(I){let d=[],E=new Set;for(let M of I){let R=M?.trim();if(!R||E.has(R))continue;E.add(R),d.push(R)}return d}function CI(I){return{...I,args:I.args&&I.args.length>0?[...I.args]:void 0,raw:I.raw?.trim()||void 0}}function LI(I){return[...I.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/gu)].map((d)=>d[1]??d[2]??d[3]??"").filter((d)=>d.length>0)}function yI(I){let d=[],E="",M=0,R=null;for(let P=0;P<I.length;P+=1){let O=I[P];if(R){if(E+=O,O===R&&I[P-1]!=="\\")R=null;continue}if(O==="'"||O==='"'){R=O,E+=O;continue}if(O==="("||O==="["||O==="{"){M+=1,E+=O;continue}if(O===")"||O==="]"||O==="}"){M=Math.max(0,M-1),E+=O;continue}if(O===","&&M===0){let k=E.trim();if(k.length>0)d.push(k);E="";continue}E+=O}let S=E.trim();if(S.length>0)d.push(S);return d}function a(I){let d=I.split(/\r?\n/u).map((R)=>R.trim()).find((R)=>R.length>0)??I.trim();if(!d)return;let E=d.match(/^([A-Za-z_][A-Za-z0-9_]*)\((.*)\)$/u);if(E){let[,R,S]=E;return{args:yI(S),kind:"tool_call",name:R,raw:d}}let M=LI(d);if(M.length===0)return;return{args:M.slice(1),kind:"command",name:M[0],raw:d}}function dI(I){let d=CI(I);if(d.args&&d.args.length>0)return d.args;if(d.kind==="warning"||!d.raw||d.raw.trim().length===0)return;let E=LI(d.raw);return E.length>1?E.slice(1):void 0}function qI(I,d){if(d.length===0)return!0;let E=0;for(let M of d){let R=!1;while(E<I.length){if(I[E]===M){R=!0,E+=1;break}E+=1}if(!R)return!1}return!0}function EI(I){let d=CI(I);return JSON.stringify({...d.args?{args:d.args}:{},kind:d.kind,name:d.name,...d.raw?{raw:d.raw}:{}})}function rI(I,d){if(!I||!d)return I===d;return EI(I)===EI(d)}function $E(I,d){if(!I||!d)return I===d;if(I.kind!==d.kind||I.name.trim()!==d.name.trim())return!1;if(d.kind==="warning")return rI(I,d);let E=dI(d);if(!E||E.length===0)return!0;let M=dI(I);if(!M||M.length===0)return!1;return qI(M,E)}function lI(I){if(!j(I))return;if(I.kind!=="command"&&I.kind!=="tool_call"&&I.kind!=="warning"||typeof I.name!=="string")return;let d=Array.isArray(I.args)&&I.args.every((E)=>typeof E==="string")?[...I.args]:void 0;return{...d?{args:d}:{},kind:I.kind,name:I.name,...typeof I.raw==="string"?{raw:I.raw}:{}}}function GI(I){if(!j(I))return;let d=g(I.prefixes),E=g(I.required),M=g(I.suffixes);if(!d&&!E&&!M)return;return{...d?{prefixes:d}:{},...E?{required:E}:{},...M?{suffixes:M}:{}}}function e(I){if(!j(I)||typeof I.from!=="string"||typeof I.to!=="string")return;let d=I.from.trim(),E=I.to.trim();if(d.length===0||E.length===0)return;return{from:d,to:E}}function aI(I){if(!j(I)||typeof I.check!=="string")return;let d=I.check.trim();if(d.length===0)return;let E=g(I.allowedStates),M=typeof I.fallbackInstruction==="string"&&I.fallbackInstruction.trim().length>0?I.fallbackInstruction.trim():void 0,R=typeof I.subject==="string"&&I.subject.trim().length>0?I.subject.trim():void 0;return{...E?{allowedStates:E}:{},check:d,...M?{fallbackInstruction:M}:{},...R?{subject:R}:{}}}function AI(I){if(!j(I)||typeof I.warningMessage!=="string")return;let d=I.warningMessage.trim();if(d.length===0)return;let E=g(I.preferredAlternatives),M=typeof I.replacementTarget==="string"&&I.replacementTarget.trim().length>0?I.replacementTarget.trim():void 0,R=typeof I.backupMention==="string"&&I.backupMention.trim().length>0?I.backupMention.trim():void 0;return{...R?{backupMention:R}:{},...E?{preferredAlternatives:E}:{},...M?{replacementTarget:M}:{},warningMessage:d}}function eI(I){if(!j(I)||typeof I.precondition!=="string")return;let d=I.precondition.trim(),E=AI(I.fallbackBehavior);if(d.length===0||!E)return;let M=g(I.allowedWhen),R=typeof I.subject==="string"&&I.subject.trim().length>0?I.subject.trim():void 0;return{...M?{allowedWhen:M}:{},fallbackBehavior:E,precondition:d,...R?{subject:R}:{}}}function t(I){if(!j(I)||typeof I.example!=="string"||typeof I.host!=="string"||I.pathPlacement!=="path_after_host"||I.scheme!=="http"&&I.scheme!=="https")return;let d=I.example.trim(),E=I.host.trim();if(d.length===0||E.length===0)return;return{example:d,host:E,pathPlacement:"path_after_host",scheme:I.scheme}}function i(I){if(!j(I)||typeof I.anchor!=="string"||typeof I.example!=="string"||I.variableSegment!=="filename")return;let d=I.anchor.trim(),E=I.example.trim();if(d.length===0||E.length===0)return;return{anchor:d,example:E,variableSegment:"filename"}}function sI(I){if(!j(I)||typeof I.kind!=="string")return;if(I.kind==="recurrence"){if(typeof I.sequenceName!=="string"||typeof I.expression!=="string")return;let d=I.sequenceName.trim(),E=I.expression.trim(),M=Array.isArray(I.baseCases)?I.baseCases.map((R)=>{if(!j(R)||typeof R.index!=="number"||typeof R.value!=="number"||!Number.isInteger(R.index)||!Number.isFinite(R.value))return;return{index:R.index,value:R.value}}).filter((R)=>Boolean(R)):void 0;if(d.length===0||E.length===0)return;return{...M&&M.length>0?{baseCases:M}:{},expression:E,kind:"recurrence",sequenceName:d}}if(I.kind==="binary_operator"){if(typeof I.expression!=="string"||typeof I.leftVariable!=="string"||typeof I.operatorSymbol!=="string"||typeof I.rightVariable!=="string")return;let d=I.expression.trim(),E=I.leftVariable.trim(),M=I.operatorSymbol.trim(),R=I.rightVariable.trim();if(d.length===0||E.length===0||M.length===0||R.length===0)return;return{expression:d,kind:"binary_operator",leftVariable:E,operatorSymbol:M,rightVariable:R}}return}function tI(I){if(!j(I)||I.kind!=="rewrite_output_slot")return;let d=GI(I.exactFragments),E=i(I.pathTemplate),M=g(I.preferredAlternatives),R=g(I.preferredFragments),S=Array.isArray(I.replacementPairs)?I.replacementPairs.map((k)=>e(k)).filter((k)=>Boolean(k)):void 0,P=t(I.urlTemplate),O=sI(I.computedResponseRule);if(!O&&!d&&!E&&!M&&!R&&!S&&!P)return;return{...O?{computedResponseRule:O}:{},...d?{exactFragments:d}:{},kind:"rewrite_output_slot",...E?{pathTemplate:E}:{},...M?{preferredAlternatives:M}:{},...R?{preferredFragments:R}:{},...S&&S.length>0?{replacementPairs:S}:{},...P?{urlTemplate:P}:{}}}function iI(I){if(!j(I)||I.kind!=="require_warning"||typeof I.warningMessage!=="string")return;let d=I.warningMessage.trim();if(d.length===0)return;let E=g(I.preferredAlternatives),M=i(I.pathTemplate),R=typeof I.replacementTarget==="string"&&I.replacementTarget.trim().length>0?I.replacementTarget.trim():void 0,S=t(I.urlTemplate),P=typeof I.backupMention==="string"&&I.backupMention.trim().length>0?I.backupMention.trim():void 0;return{...P?{backupMention:P}:{},kind:"require_warning",...M?{pathTemplate:M}:{},...E?{preferredAlternatives:E}:{},...R?{replacementTarget:R}:{},...S?{urlTemplate:S}:{},warningMessage:d}}function pI(I){if(!j(I)||I.kind!=="block_surface")return;let d=g(I.forbiddenFragments);if(!d)return;let E=Array.isArray(I.replacementPairs)?I.replacementPairs.map((R)=>e(R)).filter((R)=>Boolean(R)):void 0,M=typeof I.fallbackAnswer==="string"&&I.fallbackAnswer.trim().length>0?I.fallbackAnswer.trim():void 0;return{...M?{fallbackAnswer:M}:{},forbiddenFragments:d,kind:"block_surface",...E&&E.length>0?{replacementPairs:E}:{}}}function nI(I){if(!j(I)||I.kind!=="require_precondition_check"||typeof I.precondition!=="string")return;let d=I.precondition.trim(),E=AI(I.fallbackBehavior);if(d.length===0||!E)return;let M=g(I.allowedWhen),R=typeof I.subject==="string"&&I.subject.trim().length>0?I.subject.trim():void 0;return{...M?{allowedWhen:M}:{},fallbackBehavior:E,kind:"require_precondition_check",precondition:d,...R?{subject:R}:{}}}function uI(I){return tI(I)??iI(I)??pI(I)??nI(I)}function Id(I){if(!j(I)||!Array.isArray(I.operations))return;let d=I.operations.map((E)=>uI(E)).filter((E)=>Boolean(E));if(d.length===0)return;return{...I.bulletOnly===!0?{bulletOnly:!0}:{},...I.brevityOnly===!0?{brevityOnly:!0}:{},concise:I.concise!==!1,operations:d}}function dd(I){if(!j(I))return;let d=g(I.actionSummaryContains),E=g(I.queryContains),M=g(I.argumentOrder),R=GI(I.exactFragments),S=g(I.forbiddenFragments),P=g(I.preferredAlternatives),O=g(I.preferredFragments),k=i(I.pathTemplate),C=sI(I.computedResponseRule),L=Array.isArray(I.replacementPairs)?I.replacementPairs.map((U)=>e(U)).filter((U)=>Boolean(U)):void 0,A=t(I.urlTemplate),K=aI(I.guard),V=eI(I.guardedBehavior)??(K?{allowedWhen:K.allowedStates,fallbackBehavior:{warningMessage:K.fallbackInstruction??"Warn or defer instead of assuming the precondition already passed."},precondition:K.check,...K.subject?{subject:K.subject}:{}}:void 0),W=lI(I.canonicalFirstAction),x=Id(I.textResponsePlan),H=typeof I.appliesTo==="string"?Q(I.appliesTo):void 0,B=typeof I.fallbackInstruction==="string"&&I.fallbackInstruction.trim().length>0?I.fallbackInstruction.trim():void 0;return{...d?{actionSummaryContains:d}:{},...H?{appliesTo:H}:{},...M?{argumentOrder:M}:{},...W?{canonicalFirstAction:W}:{},...C?{computedResponseRule:C}:{},...R?{exactFragments:R}:{},...B?{fallbackInstruction:B}:{},...S?{forbiddenFragments:S}:{},...K?{guard:K}:{},...V?{guardedBehavior:V}:{},...P?{preferredAlternatives:P}:{},...O?{preferredFragments:O}:{},...k?{pathTemplate:k}:{},...E?{queryContains:E}:{},...L&&L.length>0?{replacementPairs:L}:{},...x?{textResponsePlan:x}:{},...A?{urlTemplate:A}:{}}}function j(I){return typeof I==="object"&&I!==null}function g(I){if(!Array.isArray(I)||!I.every((E)=>typeof E==="string"))return;let d=D(I);return d.length>0?d:void 0}function Ed(I){if(!j(I))return;if(I.behavioralKind!=="preference"&&I.behavioralKind!=="avoidance"&&I.behavioralKind!=="guarded_policy"&&I.behavioralKind!=="format_contract"&&I.behavioralKind!=="first_action"&&I.behavioralKind!=="syntax_constraint"&&I.behavioralKind!=="transformation_rule"&&I.behavioralKind!=="exemplar_fact")return;if(I.transferMode!=="example_only"&&I.transferMode!=="pattern_bounded"&&I.transferMode!=="general")return;if(I.enactmentSurface!=="text_response"&&I.enactmentSurface!=="host_action")return;return{behavioralKind:I.behavioralKind,enactmentSurface:I.enactmentSurface,applicability:dd(I.applicability)??{},transferMode:I.transferMode}}function Md(I){return JSON.stringify(I)}function Rd(I){if(I.enactmentSurface==="host_action")return!1;let d=I.applicability;return Boolean(d.argumentOrder||d.canonicalFirstAction||d.exactFragments||d.fallbackInstruction||d.forbiddenFragments&&d.forbiddenFragments.length>0||d.guard||d.guardedBehavior||d.pathTemplate||d.preferredAlternatives&&d.preferredAlternatives.length>0||d.replacementPairs&&d.replacementPairs.length>0||d.textResponsePlan||d.urlTemplate)}function XE(I,d){return{...I??{},[OI]:Md(d),...Rd(d)?{[kI]:!0}:{},[bI]:mI}}function Sd(I){let d=I?.[OI];if(typeof d!=="string"||d.trim().length===0)return;try{return Ed(JSON.parse(d))}catch{return}}function DI(I){return Sd(I.attributes)}function YE(I){return I.attributes?.[kI]===!0}function Pd(I){if(I.exemplarCount!==void 0&&I.exemplarCount<=1&&!I.hasGeneralRuleMarker)return"example_only";if(I.hasGeneralRuleMarker)return"general";return(I.exemplarCount??0)>=2?"pattern_bounded":"example_only"}function MI(I,d){let E=d==="prefix"?[/\b(?:start|begin)(?:[^"'`]+)?with\s+["'`]([^"'`]+)["'`]/iu,/\b(?:open|greet)(?:[^"'`]+)?with\s+["'`]([^"'`]+)["'`]/iu,/\b(?:use|with|and)\s+["'`]([^"'`]+)["'`]\s+as\s+the\s+(?:opener|greeting)/iu]:[/\b(?:end|close|sign off)(?:[^"'`]+)?with\s+["'`]([^"'`]+)["'`]/iu,/\b(?:use|and)\s+["'`]([^"'`]+)["'`]\s+as\s+the\s+closing/iu,/\bsign off(?:[^"'`]+)?as\s+["'`]([^"'`]+)["'`]/iu];for(let M of E){let S=I.match(M)?.[1]?.trim();if(S)return S}return}function Od(I){return/\b(?:plus\s+your\s+name|followed\s+by\s+the\s+sender'?s\s+name)\b/iu.test(I)}function kd(I,d){if(!I)return;if(!Od(d)||/\bname\b/iu.test(I))return I;return`${I}
Name`}function xd(I){let d=[...I.matchAll(/["'`]([^"'`]+)["'`]/gu)].map((M)=>M[1]?.trim()).filter((M)=>Boolean(M)),E=D([...d,/\bsubject line\b/iu.test(I)?"Subject:":void 0]);return E.length>0?E:void 0}function _d(I){let d=[...[...I.matchAll(/\bavoid\s+(?:the\s+)?(?:term|phrase)\s+["'`]([^"'`]+)["'`]/giu)].map((M)=>M[1]?.trim()),...[...I.matchAll(/\bavoid\s+(?:the\s+)?term\s+([A-Za-z][A-Za-z0-9_-]*)\b/giu)].map((M)=>M[1]?.trim())].filter((M)=>Boolean(M)),E=D(d);return E.length>0?E:void 0}function Cd(I){if(!/\b(?:only|strictly)\s+first-person\b/iu.test(I)&&!/\bfirst-person\s+only\b/iu.test(I)&&!/\bonly\s+first-person\s+pronouns\b/iu.test(I))return;return["you","your","yours","he","him","his","she","her","hers","they","them","their","theirs","it","its","we","us","our","ours"]}function Ld(I){if(!/\banalogy\b/iu.test(I)&&!/\bsimile\b/iu.test(I)&&!/\bsimiles\b/iu.test(I))return;return["like"]}function RI(I){let d=[];for(let M of oI){let S=I.match(M)?.[1]?.trim();if(S)d.push(S)}let E=D(d);return E.length>0?E:void 0}function Gd(I){let d=[...I.matchAll(/(?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9_/-]/gu)].map((M)=>M[0]?.trim()).filter((M)=>Boolean(M)),E=D(d);return E.length>0?E:void 0}function Ad(I){let d=[],E=new Set(["url","urls","file","files","warning","warnings"]);for(let R of[/\buse\s+([A-Z][A-Za-z0-9_]*(?:\s+specialist)?)\s+or\s+warn\b/giu,/\bprefer\s+([A-Z][A-Za-z0-9_]*|[a-z_]+_[a-z0-9_]*)\s+or\s+(?:a|an)\s+warning\b/giu,/\bprefer\s+([A-Z][A-Za-z0-9_]*|[a-z_]+_[a-z0-9_]*)\b/giu,/\bchoose\s+([A-Z][A-Za-z0-9_]*(?:\/[A-Za-z][A-Za-z0-9_ -]*)*)\s+instead\b/giu])for(let S of I.matchAll(R)){let P=S[1]?.trim();if(!P)continue;for(let O of P.split("/")){let k=O.trim();if(!k||E.has(k.toLowerCase()))continue;d.push(k)}}let M=D(d);return M.length>0?M:void 0}function sd(I){let d=I.match(/\b(?:do not|don't|avoid|never)\b[\s\S]{0,120}?([A-Za-z0-9_-]+\.[A-Za-z0-9]{2,8}|\.[A-Za-z0-9]{2,8})[\s\S]{0,100}?\b(?:use|prefer|choose)\s+([A-Za-z0-9_-]+\.[A-Za-z0-9]{2,8}|\.[A-Za-z0-9]{2,8})\s+instead\b/iu),E=I.match(/\b(?:use|prefer|choose)\s+([A-Za-z0-9_-]+\.[A-Za-z0-9]{2,8}|\.[A-Za-z0-9]{2,8})\s+instead\s+of\s+([A-Za-z0-9_-]+\.[A-Za-z0-9]{2,8}|\.[A-Za-z0-9]{2,8})\b/iu),M=I.match(/\bprefer\s+([A-Za-z0-9_-]+\.[A-Za-z0-9]{2,8}|\.[A-Za-z0-9]{2,8})\s+or\s+warn\s+(?:about|against|on)\s+([A-Za-z0-9_-]+\.[A-Za-z0-9]{2,8}|\.[A-Za-z0-9]{2,8})\b/iu),R=d?.[1]??E?.[2]??M?.[2],S=d?.[2]??E?.[1]??M?.[1];if(!R||!S||!II.test(R)||!II.test(S))return null;let P=R.match(u)?.[0],O=S.match(u)?.[0],k=[];if(!R.startsWith(".")||S.startsWith("."))k.push({from:R,to:S});if(P&&O)k.push({from:P,to:O});return{forbiddenFragments:D([R,P]),preferredFragments:D([S,O]),replacementPairs:HI(k)}}function Dd(I){let E=I.match(/\b(?:distrusts?|do not trust|don't trust|untrusted)\s+([A-Za-z_][A-Za-z0-9_]*)\b/iu)?.[1]?.trim();if(!E)return null;let R=I.match(/\buse\s+([A-Z][A-Za-z0-9_]*(?:\s+specialist)?)\s+or\s+warn\b/iu)?.[1]?.trim();return{fallbackInstruction:`Warn and route to ${R??"a specialist path"} instead of using the distrusted default path.`,forbiddenFragments:[E],...R?{preferredAlternatives:[R]}:{},queryContains:[E]}}function gd(I){let d=[/\b(?:output|emit|return|run|use)\s+(?:the\s+)?exact\s+(?:[A-Za-z0-9_-]+\s+)?(?:command|query|syntax|line)\s+(.+?)(?:[.](?:\s|$)|$)/iu,/\b(?:first line must be exactly|exact command is|exact query is)\s+(.+?)(?:[.](?:\s|$)|$)/iu];for(let E of d){let R=I.match(E)?.[1]?.trim();if(!R)continue;return a(R)}return}function jd(I){let d=I.match(/\bBefore using\s+([A-Za-z_][A-Za-z0-9_]*)\s*,\s*check\s+(.+?)\s+first\s+and\s+only proceed when\s+(.+?)(?:[.]|$)/iu);if(!d)return;let E=d[1]?.trim(),M=d[2]?.trim(),R=d[3]?.trim();if(!M)return;let S=D(R?.split(/\bor\b|,/iu).map((P)=>P.replace(/\b(?:is|are|equals?)\b/giu," ").replace(/\s+/gu," ").trim())??[]);return{...S.length>0?{allowedStates:S}:{},check:M,fallbackInstruction:`Check ${M} first${S.length>0?` and only proceed when ${S.join(" or ")}`:""}; otherwise warn or defer instead of assuming it already passed.`,...E?{subject:E}:{}}}function Hd(I){let d=s(I);if(!d.includes("https")||!d.includes("http"))return null;if(!d.includes("prefer https")&&!d.includes("prefer urls in the form https://")&&!d.includes("avoid http")&&!d.includes("warn instead of producing http"))return null;let E=I.match(/(https:\/\/[A-Za-z0-9.-]+\/<page>)/u),M,R;if(E?.[1]){let S=E[1].trim(),P=new URL(S.replace(wI,"page"));M=[`${P.protocol}//${P.host}/`],R={example:S,host:P.host,pathPlacement:"path_after_host",scheme:P.protocol==="https:"?"https":"http"}}return{fallbackInstruction:"If the current probe explicitly requests http, warn first and then offer the https URL instead of silently substituting protocols.",forbiddenFragments:[n.from],...M?{preferredFragments:M}:{},queryContains:["url"],replacementPairs:[n],...R?{urlTemplate:R}:{}}}function Nd(I){let d=s(I),E=I.match(/\bdo not write under\s+((?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9_/-])/iu)?.[1]??(Gd(I)??[]).find((P)=>P.startsWith("/root")||P.startsWith("/system")||P.startsWith("/etc")),M=I.match(/(?:in the form|under)\s+(~\/[A-Za-z0-9._/-]+\/<file>|\/home\/[A-Za-z0-9._/-]+\/<file>)/u),R,S;if(M?.[1]){let P=M[1].trim(),O=P.replace(/<file>$/u,"");R=[O],S={anchor:O,example:P,variableSegment:"filename"}}if(!E&&!d.includes("home-directory")&&!S)return null;return{fallbackInstruction:"Refuse the unsafe path and redirect to a safe user-writable home-directory path instead.",...E?{forbiddenFragments:[E]}:{},...R?{preferredFragments:R}:d.includes("home-directory")?{preferredFragments:["/home/"]}:{},...S?{pathTemplate:S}:{}}}function gI(I){if(!/\bback\s*up\b|\bbackup\b/iu.test(I))return;return"Mention a safe backup before proceeding."}function Ud(I){return I?.[0]}function Kd(I){let d=I.fallbackInstruction??(I.preferredAlternatives&&I.preferredAlternatives.length>0?`Warn first and redirect to ${I.preferredAlternatives.join(" or ")} instead of proceeding directly.`:void 0);if(!d)return;return{...I.backupMention?{backupMention:I.backupMention}:{},...I.preferredAlternatives&&I.preferredAlternatives.length>0?{preferredAlternatives:[...I.preferredAlternatives]}:{},...I.replacementTarget?{replacementTarget:I.replacementTarget}:{},warningMessage:d}}function $(I){let d=[],E={...I.applicability.computedResponseRule?{computedResponseRule:I.applicability.computedResponseRule}:{},kind:"rewrite_output_slot",...I.applicability.exactFragments?{exactFragments:I.applicability.exactFragments}:{},...I.applicability.pathTemplate?{pathTemplate:I.applicability.pathTemplate}:{},...I.applicability.preferredAlternatives&&I.applicability.preferredAlternatives.length>0?{preferredAlternatives:I.applicability.preferredAlternatives}:{},...I.applicability.preferredFragments&&I.applicability.preferredFragments.length>0?{preferredFragments:I.applicability.preferredFragments}:{},...I.applicability.replacementPairs&&I.applicability.replacementPairs.length>0?{replacementPairs:I.applicability.replacementPairs}:{},...I.applicability.urlTemplate?{urlTemplate:I.applicability.urlTemplate}:{}};if(E.computedResponseRule||E.exactFragments||E.pathTemplate||E.preferredAlternatives||E.preferredFragments||E.replacementPairs||E.urlTemplate)d.push(E);if(I.applicability.forbiddenFragments&&I.applicability.forbiddenFragments.length>0)d.push({forbiddenFragments:[...I.applicability.forbiddenFragments],kind:"block_surface",...I.applicability.replacementPairs&&I.applicability.replacementPairs.length>0?{replacementPairs:I.applicability.replacementPairs}:{}});if(I.applicability.guardedBehavior)d.unshift({...I.applicability.guardedBehavior.allowedWhen?{allowedWhen:I.applicability.guardedBehavior.allowedWhen}:{},fallbackBehavior:I.applicability.guardedBehavior.fallbackBehavior,kind:"require_precondition_check",precondition:I.applicability.guardedBehavior.precondition,...I.applicability.guardedBehavior.subject?{subject:I.applicability.guardedBehavior.subject}:{}});else{let M=Kd({backupMention:gI(I.applicability.fallbackInstruction??""),fallbackInstruction:I.applicability.fallbackInstruction,preferredAlternatives:I.applicability.preferredAlternatives,replacementTarget:Ud(I.applicability.preferredAlternatives)});if(M&&(I.behavioralKind==="avoidance"||I.behavioralKind==="preference"||I.behavioralKind==="transformation_rule"||M.preferredAlternatives&&M.preferredAlternatives.length>0||M.backupMention||M.replacementTarget))d.push({...M.backupMention?{backupMention:M.backupMention}:{},kind:"require_warning",...I.applicability.pathTemplate?{pathTemplate:I.applicability.pathTemplate}:{},...M.preferredAlternatives?{preferredAlternatives:M.preferredAlternatives}:{},...M.replacementTarget?{replacementTarget:M.replacementTarget}:{},...I.applicability.urlTemplate?{urlTemplate:I.applicability.urlTemplate}:{},warningMessage:M.warningMessage})}return d.length>0?{concise:!0,operations:d}:void 0}function $d(I){let d=s(I);return zI.some((E)=>d.includes(E))}function r(I){let d=s(I);return hI.some((E)=>d.includes(E))}function Xd(I){let d=s(I);if(fI.some((E)=>d.includes(E)))return!0;return jI(I)!==void 0}function jI(I){for(let d of vI){let M=I.match(d)?.[1]?.trim();if(!M)continue;let R=M.match(/^([A-Za-z_][A-Za-z0-9_]*)\((.*)\)$/u);if(R){let P=R[1];if(!p.has(s(P)))return P;continue}let S=M.split(/\s+/u)[0]?.trim();if(S&&!p.has(s(S)))return S}return}function Yd(I){let d=[...I.matchAll(/\b([a-z_][a-z0-9_ -]+?)\s+(first|second|third)\b/giu)];if(d.length===0)return;let E=new Map;for(let R of d){let P=R[1]?.trim().replace(/\s+/gu," ").replace(/.*\b(?:takes|use|with)\s+/iu,"")?.replace(/^(?:and|then)\s+/iu,""),O=R[2]?.toLowerCase();if(!P||!O)continue;E.set(O,P)}let M=["first","second","third"].map((R)=>E.get(R)).filter((R)=>Boolean(R));return M.length>0?M:void 0}function Zd(I){let d=s(I);return FI.some((E)=>d.includes(E))}function Jd(I){let d=I.match(/\b([A-Z][A-Za-z0-9_]*)\(n\)\s*=\s*([^.\n]+?)(?:\.|\n|$)/u);if(d?.[1]&&d[2]){let M=d[1].trim(),R=d[2].trim(),S=[...I.matchAll(new RegExp(`${F(M)}\\((-?\\d+)\\)\\s*=\\s*(-?\\d+(?:\\.\\d+)?)`,"gu"))].map((P)=>{let O=Number(P[1]),k=Number(P[2]);if(!Number.isInteger(O)||!Number.isFinite(k))return;return{index:O,value:k}}).filter((P)=>Boolean(P));return{...S.length>0?{baseCases:S}:{},expression:R,kind:"recurrence",sequenceName:M}}let E=I.match(/\b([a-z])\s*([⊗⊕⊖Ω])\s*([a-z])\s*=\s*([^.\n]+?)(?:\.|\n|$)/u);if(E?.[1]&&E[2]&&E[3]&&E[4])return{expression:E[4].trim(),kind:"binary_operator",leftVariable:E[1].trim(),operatorSymbol:E[2].trim(),rightVariable:E[3].trim()};return}function Td(I){let d=Zd(I.rule),E=Pd({exemplarCount:I.exemplarCount,hasGeneralRuleMarker:d}),M=RI(I.rule),R=Q(I.appliesTo),S=Hd(I.rule),P=Nd(I.rule),O=sd(I.rule),k=Dd(I.rule),C=gd(I.rule),L=Jd(I.rule),A=D([...Ad(I.rule)??[],...k?.preferredAlternatives??[]]),K=_d(I.rule),V=Cd(I.rule),W=Ld(I.rule),x=jd(I.rule),H=D([...RI(I.rule)??[],...x?.check?[x.check]:[],...x?.subject?[x.subject]:[],...S?.queryContains??[],...k?.queryContains??[]]),B=gI(I.rule),U=D([...K??[],...V??[],...S?.forbiddenFragments??[],...P?.forbiddenFragments??[],...O?.forbiddenFragments??[],...k?.forbiddenFragments??[]]),X=D([...W??[],...S?.preferredFragments??[],...P?.preferredFragments??[],...O?.preferredFragments??[]]),Y=P?.pathTemplate,N=HI([...S?.replacementPairs??[],...O?.replacementPairs??[]]),Z=S?.urlTemplate,J=x?.fallbackInstruction??k?.fallbackInstruction??S?.fallbackInstruction??P?.fallbackInstruction??(A.length>0&&r(I.rule)?`Prefer ${A.join(" or ")}${B?" and mention a safe backup before proceeding":""} or warn instead of implying the avoided behavior.`:void 0),G=x?{...x.allowedStates?{allowedWhen:x.allowedStates}:{},fallbackBehavior:{...B?{backupMention:B}:{},...A.length>0?{preferredAlternatives:A}:{},...A[0]?{replacementTarget:A[0]}:{},warningMessage:x.fallbackInstruction??"Warn or defer instead of assuming the required precondition already passed."},precondition:x.check,...x.subject?{subject:x.subject}:{}}:void 0;if(C||Xd(I.rule)){let _=jI(I.rule),z=Yd(I.rule);return{behavioralKind:r(I.rule)||I.kind==="dont"?"first_action":"syntax_constraint",enactmentSurface:"host_action",applicability:{appliesTo:R,...C?{canonicalFirstAction:C}:_?{canonicalFirstAction:{kind:_.includes("_")?"tool_call":"command",name:_}}:{},...z?{argumentOrder:z}:{},...M&&!C?{queryContains:M}:{}},transferMode:E==="general"?"pattern_bounded":E}}if($d(I.rule)){let _=MI(I.rule,"prefix"),z=MI(I.rule,"suffix"),b=kd(z,I.rule),o=D([...(xd(I.rule)??[]).filter((WI)=>WI!==z),_,b]);return{behavioralKind:"format_contract",enactmentSurface:"text_response",applicability:{appliesTo:R,exactFragments:{..._?{prefixes:[_]}:{},...o.length>0?{required:o}:{},...b?{suffixes:[b]}:{}},...M?{queryContains:M}:{},textResponsePlan:$({behavioralKind:"format_contract",applicability:{appliesTo:R,exactFragments:{..._?{prefixes:[_]}:{},...o.length>0?{required:o}:{},...b?{suffixes:[b]}:{}},...M?{queryContains:M}:{}}})},transferMode:E}}if(I.kind==="prefer"){let _={appliesTo:R,...J?{fallbackInstruction:J}:{},...L?{computedResponseRule:L}:{},...U.length>0?{forbiddenFragments:U}:{},...x?{guard:x}:{},...G?{guardedBehavior:G}:{},...A.length>0?{preferredAlternatives:A}:{},...X.length>0?{preferredFragments:X}:{},...Y?{pathTemplate:Y}:{},...H.length>0?{queryContains:H}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:G?"guarded_policy":"preference",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:G?"guarded_policy":"preference",applicability:_})?{textResponsePlan:$({behavioralKind:G?"guarded_policy":"preference",applicability:_})}:{}},transferMode:E}}if(I.kind==="dont"||r(I.rule)){let _={appliesTo:R,...J?{fallbackInstruction:J}:{},...L?{computedResponseRule:L}:{},...U.length>0?{forbiddenFragments:U}:{},...x?{guard:x}:{},...G?{guardedBehavior:G}:{},...A.length>0?{preferredAlternatives:A}:{},...X.length>0?{preferredFragments:X}:{},...Y?{pathTemplate:Y}:{},...H.length>0?{queryContains:H}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:G?"guarded_policy":"avoidance",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:G?"guarded_policy":"avoidance",applicability:_})?{textResponsePlan:$({behavioralKind:G?"guarded_policy":"avoidance",applicability:_})}:{}},transferMode:E}}if(I.kind==="do"&&!M){let _={appliesTo:R,...J?{fallbackInstruction:J}:{},...L?{computedResponseRule:L}:{},...U.length>0?{forbiddenFragments:U}:{},...x?{guard:x}:{},...G?{guardedBehavior:G}:{},...A.length>0?{preferredAlternatives:A}:{},...X.length>0?{preferredFragments:X}:{},...Y?{pathTemplate:Y}:{},...H.length>0?{queryContains:H}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:G?"guarded_policy":"transformation_rule",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:G?"guarded_policy":"transformation_rule",applicability:_})?{textResponsePlan:$({behavioralKind:G?"guarded_policy":"transformation_rule",applicability:_})}:{}},transferMode:d?"general":"pattern_bounded"}}if(d||(I.exemplarCount??0)>=2){let _={appliesTo:R,...J?{fallbackInstruction:J}:{},...L?{computedResponseRule:L}:{},...U.length>0?{forbiddenFragments:U}:{},...x?{guard:x}:{},...G?{guardedBehavior:G}:{},...A.length>0?{preferredAlternatives:A}:{},...X.length>0?{preferredFragments:X}:{},...Y?{pathTemplate:Y}:{},...H.length>0?{queryContains:H}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:G?"guarded_policy":"transformation_rule",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:G?"guarded_policy":"transformation_rule",applicability:_})?{textResponsePlan:$({behavioralKind:G?"guarded_policy":"transformation_rule",applicability:_})}:{}},transferMode:d?"general":"pattern_bounded"}}let q={appliesTo:R,...J?{fallbackInstruction:J}:{},...L?{computedResponseRule:L}:{},...U.length>0?{forbiddenFragments:U}:{},...x?{guard:x}:{},...G?{guardedBehavior:G}:{},...A.length>0?{preferredAlternatives:A}:{},...X.length>0?{preferredFragments:X}:{},...Y?{pathTemplate:Y}:{},...H.length>0?{queryContains:H}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:"exemplar_fact",enactmentSurface:"text_response",applicability:{...q,...$({behavioralKind:"exemplar_fact",applicability:q})?{textResponsePlan:$({behavioralKind:"exemplar_fact",applicability:q})}:{}},transferMode:"example_only"}}function c(I,d){if(!d||d.length===0)return[];let E=s(I);return d.filter((M)=>E.includes(s(M)))}function HI(I){let d=[],E=new Set;for(let M of I){if(!M)continue;let R=`${M.from}\x00${M.to}`;if(E.has(R))continue;E.add(R),d.push(M)}return d}function Wd(I){if(!I.transientFeedback||I.transientFeedback.length===0)return[];let d=Q(I.appliesTo),E=s(I.query),M=[];for(let R of I.transientFeedback){if(R.lifecycle!=="active"||R.kind==="validated_pattern")continue;if(DI(R))continue;let S=Td({appliesTo:R.appliesTo,exemplarCount:1,kind:R.kind,rule:R.rule});if(S.enactmentSurface!==I.surface)continue;let P=Q(S.applicability.appliesTo??R.appliesTo),O=P===d;if(!O&&P!=="general_response")continue;let k=D([...c(E,S.applicability.queryContains),...c(E,S.applicability.actionSummaryContains),...c(E,S.applicability.forbiddenFragments),...c(E,S.applicability.preferredFragments)]),C=k.length===0&&(I.surface==="text_response"?f(S):BI(S))&&(S.applicability.queryContains?.length??0)===0;if(S.transferMode!=="general"&&k.length===0&&!C)continue;let L=(O?1e4:0)+xI[S.behavioralKind]*100+_I[S.transferMode]*10+k.length+(C?3:0)+5;M.push({feedback:R,matchedQueryTokens:k,policy:S,score:L})}return M}function ZE(I){let d=Q(I.appliesTo),E=s(I.query),M=[];for(let S of I.feedback??[]){if(S.lifecycle!=="active")continue;let P=DI(S);if(!P||P.enactmentSurface!==I.surface)continue;let O=Q(P.applicability.appliesTo??S.appliesTo),k=O===d;if(!k&&O!=="general_response")continue;let C=D([...c(E,P.applicability.queryContains),...c(E,P.applicability.actionSummaryContains),...c(E,P.applicability.forbiddenFragments),...c(E,P.applicability.preferredFragments)]);if(P.transferMode==="example_only"&&C.length===0)continue;let L=(k?1e4:0)+(I.surface==="host_action"&&P.enactmentSurface==="host_action"?2000:0)+xI[P.behavioralKind]*100+_I[P.transferMode]*10+C.length;M.push({feedback:S,matchedQueryTokens:C,policy:P,score:L})}let R=Wd(I);return[...M,...R].sort((S,P)=>P.score-S.score)}function Qd(I){let d=new Set,E=[];for(let M of I){let R=JSON.stringify(M);if(d.has(R))continue;d.add(R),E.push(M)}return E}function JE(I){return cd(I.map((d)=>d.policy))}function cd(I){let d=Qd(I.flatMap((R)=>{if(R.enactmentSurface!=="text_response")return[];return R.applicability.textResponsePlan?.operations??$({behavioralKind:R.behavioralKind,applicability:R.applicability})?.operations??[]}));if(d.length===0)return;let E=I.some((R)=>R.applicability.textResponsePlan?.brevityOnly===!0);return{...I.some((R)=>R.applicability.textResponsePlan?.bulletOnly===!0)?{bulletOnly:!0}:{},...E?{brevityOnly:!0}:{},concise:!0,operations:d}}function Vd(I){switch(I.kind){case"rewrite_output_slot":return[I.computedResponseRule?I.computedResponseRule.kind==="recurrence"?`rewrite_output_slot recurrence_rule: ${I.computedResponseRule.sequenceName}(n) = ${I.computedResponseRule.expression}`:`rewrite_output_slot binary_rule: ${I.computedResponseRule.leftVariable} ${I.computedResponseRule.operatorSymbol} ${I.computedResponseRule.rightVariable} = ${I.computedResponseRule.expression}`:void 0,I.replacementPairs&&I.replacementPairs.length>0?`rewrite_output_slot replacements: ${I.replacementPairs.map((d)=>`${d.from} -> ${d.to}`).join(", ")}`:void 0,I.urlTemplate?`rewrite_output_slot url_template: keep ${I.urlTemplate.scheme}://${I.urlTemplate.host} and place the requested page after the host as a path segment`:void 0,I.pathTemplate?`rewrite_output_slot path_template: keep safe anchor ${I.pathTemplate.anchor} and preserve the requested filename`:void 0,I.exactFragments?.prefixes?.length?`rewrite_output_slot prefix: ${I.exactFragments.prefixes[0]}`:void 0,I.exactFragments?.suffixes?.length?`rewrite_output_slot suffix: ${I.exactFragments.suffixes[0]}`:void 0].filter((d)=>Boolean(d));case"block_surface":return[`block_surface forbidden: ${I.forbiddenFragments.join(", ")}`,I.fallbackAnswer?`block_surface fallback: ${I.fallbackAnswer}`:void 0].filter((d)=>Boolean(d));case"require_warning":return[`require_warning: ${I.warningMessage}`,I.preferredAlternatives&&I.preferredAlternatives.length>0?`warning_alternatives: ${I.preferredAlternatives.join(", ")}`:void 0,I.backupMention?`warning_backup: ${I.backupMention}`:void 0].filter((d)=>Boolean(d));case"require_precondition_check":return[`require_precondition_check: ${I.precondition}`,I.allowedWhen&&I.allowedWhen.length>0?`allowed_when: ${I.allowedWhen.join(" or ")}`:void 0,`fallback_behavior: ${I.fallbackBehavior.warningMessage}`].filter((d)=>Boolean(d))}}function TE(I){if(!I)return[];return D([...I.brevityOnly?["brevity_only: emit only the answer surface with no extra explanation"]:[],...I.bulletOnly?["bullet_only: emit a terse bullet list with no paragraph preface"]:[],...I.operations.flatMap((d)=>Vd(d))])}function F(I){return I.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function NI(I){return Number.isInteger(I)?String(I):String(Number(I.toFixed(10)))}function UI(I){let d=I.expression.replace(/\^/gu,"**");for(let[E,M]of Object.entries(I.scope).sort(([R],[S])=>S.length-R.length))d=d.replace(new RegExp(`\\b${F(E)}\\b`,"gu"),`(${M})`);if(/[^0-9+\-*/().\s*]/u.test(d))return;try{let E=Function(`"use strict"; return (${d});`)();return typeof E==="number"&&Number.isFinite(E)?E:void 0}catch{return}}function Bd(I){let d=new Map;for(let E of I.query.matchAll(new RegExp(`${F(I.sequenceName)}\\((-?\\d+)\\)\\s*=\\s*(-?\\d+(?:\\.\\d+)?)`,"gu"))){let M=Number(E[1]),R=Number(E[2]);if(!Number.isInteger(M)||!Number.isFinite(R))continue;d.set(M,R)}return d}function bd(I){let d=I.query.match(new RegExp(`${F(I.rule.sequenceName)}\\((-?\\d+)\\)(?!\\s*=)`,"u"));if(!d?.[1])return;let E=Number(d[1]);if(!Number.isInteger(E))return;let M=new Map;for(let k of I.rule.baseCases??[])M.set(k.index,k.value);for(let[k,C]of Bd({query:I.query,sequenceName:I.rule.sequenceName}))M.set(k,C);let R=new Set,S=new RegExp(`${F(I.rule.sequenceName)}\\(n\\s*([+-])\\s*(\\d+)\\)`,"gu"),P=(k)=>{if(M.has(k))return M.get(k);if(R.has(k))return;R.add(k);let C=I.rule.expression.replace(S,(A,K,V)=>{let W=Number(V);if(!Number.isInteger(W))return"NaN";let x=K==="+"?k+W:k-W,H=P(x);return H===void 0?"NaN":`(${H})`});C=C.replace(/\bn\b/gu,`(${k})`);let L=UI({expression:C,scope:{}});if(R.delete(k),L===void 0)return;return M.set(k,L),L},O=P(E);return O===void 0?void 0:NI(O)}function md(I){let d=I.query.match(new RegExp(`(-?\\d+(?:\\.\\d+)?)\\s*${F(I.rule.operatorSymbol)}\\s*(-?\\d+(?:\\.\\d+)?)`,"u"));if(!d?.[1]||!d[2])return;let E=Number(d[1]),M=Number(d[2]);if(!Number.isFinite(E)||!Number.isFinite(M))return;let R=UI({expression:I.rule.expression,scope:{[I.rule.leftVariable]:E,[I.rule.rightVariable]:M}});return R===void 0?void 0:NI(R)}function WE(I){if(!I.query||!I.rule)return;switch(I.rule.kind){case"recurrence":return bd({query:I.query,rule:I.rule});case"binary_operator":return md({query:I.query,rule:I.rule})}}function l(I){if(I.startsWith("~/")){let d=I.slice(2).split("/").filter(Boolean);return d.length>0?`|~|${d.join("|")}|`:"|~|"}if(I.startsWith("/")){let d=I.split("/").filter(Boolean);return d.length>0?`|${d.join("|")}|`:"|/|"}return`|${I}|`}function KI(I){if(!I)return;return(I.match(/\b(?:named|called)\s+([A-Za-z0-9._/-]+)/iu)?.[1]??I.match(/\b(?:folder|subfolder|directory)\s+(?:named\s+)?([A-Za-z0-9._/-]+)/iu)?.[1]??h(I)[0])?.trim().replace(/[.,;:!?]+$/u,"")}function Fd(I){if(!I)return;let d=I.replace(/\s+/gu," ").trim(),E=d.match(/(?:under|inside|within|beneath)\s+((?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._-])/iu)?.[1]??d.match(/\b(?:directory|path|folder)\s+(?:named\s+)?((?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._-])/iu)?.[1]??d.match(/((?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._-])/u)?.[1],M=d.match(/\b(?:app|folder|subfolder|directory)\s+named\s+([A-Za-z0-9._-]+)/iu)?.[1]??d.match(/\bcalled\s+([A-Za-z0-9._-]+)/iu)?.[1],R=E?.replace(/[.,;:!?]+$/u,""),S=M?.replace(/[.,;:!?]+$/u,"");if(R){let O=R.endsWith("/")?`${R}${S??""}`.replace(/\/+$/u,""):S?`${R}/${S}`:R;return l(O)}let P=KI(I);return P?l(P):void 0}function w(I){return h(I??"")[0]?.trim()}function m(I,d){if(!I)return[];return[...I.matchAll(d)].map((E)=>E[1]?.trim()).filter((E)=>Boolean(E))}function zd(I,d){let E=w(I);if(!E)return;let R=/_<token>|<token>_/u.test(d??"")?E.replace(/[^A-Za-z0-9]+/gu,"_").replace(/^_+|_+$/gu,""):E.replace(/[^A-Za-z0-9]/gu,"");return R&&R.length>0?R:void 0}function fd(I){if(!I)return;let d=h(I);if(d.length>=2)return d.map((E)=>E.trim()).filter(Boolean).join(" ");if(d[0])return d[0].trim();return I.match(/\b(?:terms?|tags?|records?)\s+([A-Za-z0-9_-]+(?:\s+and\s+[A-Za-z0-9_-]+)+)/iu)?.[1]?.replace(/\s+and\s+/giu," ").trim()}function $I(I){if(!I)return;return I.match(/\b([A-Za-z_][A-Za-z0-9_.-]*)\s*(?:>=|<=|=|>|<)\s*(?:['"]?[A-Za-z0-9_.-]+['"]?)/u)?.[1]??I.match(/\b(?:whose|with|where|filter(?:ed)?\s+by|based\s+on)\s+([A-Za-z_][A-Za-z0-9_.-]*)\s+(?:is\s+)?(?:after|before|earlier|older|younger|more|less|above|below|over|under|greater|equal|equals|=|>|<)\b/iu)?.[1]??I.match(/\b(?:whose|with|where)\s+([A-Za-z_][A-Za-z0-9_.-]*)\s+is\s+(?:an?\s+|the\s+)?[A-Za-z_][A-Za-z0-9_.-]*\b/iu)?.[1]??(/\b(?:older|younger)\s+than\b/iu.test(I)?"age":void 0)??I.match(/\b([A-Za-z_][A-Za-z0-9_.-]*)\s+(?:is\s+)?(?:after|before|earlier|older|younger|more|less|above|below|over|under|greater|equal|equals)\b/iu)?.[1]}function XI(I){let d=s(I);if(/\b(?:older|greater|more|above|over|after)\b(?:\s+than)?(?:\s+-?\d|\s+\w+\s+-?\d|\b)/u.test(d))return">";if(/\b(?:younger|less|below|under|before|earlier)\b(?:\s+than)?(?:\s+-?\d|\s+\w+\s+-?\d|\b)/u.test(d))return"<";if(/\b(?:at\s+least|minimum|no\s+less\s+than)\b/u.test(d))return">=";if(/\b(?:at\s+most|maximum|no\s+more\s+than)\b/u.test(d))return"<=";if(/\b(?:equal|equals|exactly|is)\b/u.test(d))return"=";return}function hd(I){if(/^-?\d+(?:\.\d+)?$/u.test(I))return I;if(/^['"].*['"]$/u.test(I))return I;return`'${I}'`}function od(I){return I.replace(/^['"]|['"]$/gu,"").replace(/[.,;:!?]+$/u,"")}function YI(I){if(!I)return;let d=I.match(/\b(?:>=|<=|=|>|<)\s*(['"]?[A-Za-z0-9_.-]+['"]?)/u)?.[1]??I.match(/\b(?:after|before|earlier\s+than|older\s+than|younger\s+than|more\s+than|less\s+than|above|below|over|under|greater\s+than|equal(?:s)?(?:\s+to)?)\s+(['"]?[A-Za-z0-9_.-]+['"]?)/iu)?.[1]??I.match(/\bis\s+(?:an?|the)\s+([A-Za-z_][A-Za-z0-9_.-]*)\b/iu)?.[1];if(d)return hd(od(d));let E=I.match(/\b\d{4}-\d{2}-\d{2}\b/u)?.[0];if(E)return`'${E}'`;return I.match(/\b-?\d+(?:\.\d+)?\b/u)?.[0]}function vd(I,d){if(!d)return;let E=I.match(/^(.+\|\s*FILTER\s+)[A-Za-z_][A-Za-z0-9_.-]*\s*(?:>=|<=|=|>|<)\s*.+$/iu);if(!E?.[1])return;let M=$I(d),R=XI(d),S=YI(d);if(!M||!R||!S)return;return`${E[1]}${M} ${R} ${S}`}function wd(I,d){let E=I;if(E.includes("|folder|")){let M=KI(d);if(!M)return;E=E.replace(/\|folder\|/gu,l(M))}if(E.includes("|path|")){let M=Fd(d);if(!M)return;E=E.replace(/\|path\|/gu,M)}if(E.includes("<filename>")){let M=w(d);if(!M)return;E=E.replace(/<filename>/gu,M)}if(E.includes("<id>")){let M=w(d);if(!M)return;E=E.replace(/<id>/gu,M)}if(E.includes("<item>")){let M=w(d);if(!M)return;E=E.replace(/<item>/gu,M)}if(E.includes("<qty>")){let M=d?.match(/\bqty\b[^0-9]*([0-9]+)/iu)?.[1]??d?.match(/\b([0-9]+)\b/u)?.[1];if(!M)return;E=E.replace(/<qty>/gu,M)}if(E.includes("<terms>")){let M=fd(d);if(!M)return;E=E.replace(/<terms>/gu,M)}if(E.includes("<token>")){let M=zd(d,E);if(!M)return;E=E.replace(/<token>/gu,M)}if(E.includes("<field>")){let M=$I(d);if(!M)return;E=E.replace(/<field>/gu,M)}if(E.includes("<operator>")){let M=XI(d);if(!M)return;E=E.replace(/<operator>/gu,M)}if(E.includes("<value>")){let M=YI(d);if(!M)return;E=E.replace(/<value>/gu,M)}return/<[^>]+>/u.test(E)?void 0:E}function T(I){return`'${I.replaceAll("'","\\'")}'`}function y(I){return I.replace(/[.,;:!?]+$/u,"")}function yd(I){return I.endsWith("/")}function qd(I,d){if(!yd(I))return I;let E=d.split("/").filter(Boolean).at(-1);return E?`${I}${E}`:I}function rd(I){let d=h(I),E=m(I,/\bfrom\s+['"`]([^'"`]+)['"`]/giu),M=[...I.matchAll(/\bfrom\s+((?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._-])/giu)].map((O)=>y(O[1]?.trim()??"")).filter((O)=>Boolean(O)),R=new Set([...m(I,/\binto\s+['"`]([^'"`]+)['"`]/giu),...[...I.matchAll(/\binto\s+((?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._/-])/giu)].map((O)=>y(O[1]?.trim()??"")).filter((O)=>Boolean(O))]),S=new Set(m(I,/\busing\s+['"`]([^'"`]+)['"`]/giu)),P=new Set(ZI(I));return D([...E,...M,...d.filter((O)=>!R.has(O)&&!S.has(O)&&!P.has(O))])}function ld(I){return m(I,/\binto\s+['"`]([^'"`]+)['"`]/giu)[0]??[...I.matchAll(/\binto\s+((?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._/-])/giu)].map((d)=>y(d[1]?.trim()??"")).find((d)=>Boolean(d))??m(I,/\bto\s+['"`]([^'"`]+)['"`]/giu)[0]??[...I.matchAll(/\bto\s+((?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._/-])/giu)].map((d)=>y(d[1]?.trim()??"")).find((d)=>Boolean(d))}function ad(I){return I.match(/\bowner\s+['"`]?([A-Za-z0-9._-]+)['"`]?/iu)?.[1]?.trim()??I.match(/\bas\s+owner\s+['"`]?([A-Za-z0-9._-]+)['"`]?/iu)?.[1]?.trim()}function ed(I){return I.match(/\b(?:perms?|permissions?)\s+['"`]?([0-7]{3,4})['"`]?/iu)?.[1]?.trim()??I.match(/\bmode\s+['"`]?([0-7]{3,4})['"`]?/iu)?.[1]?.trim()}function td(I){return I.match(/\bmode\s+['"`]?([A-Za-z0-9._-]+)['"`]?/iu)?.[1]?.trim()}function id(I){return I.match(/\btag\s+['"`]?([A-Za-z0-9._-]+)['"`]?/iu)?.[1]?.trim()}function ZI(I){return m(I,/\bflags?\s+['"`]([^'"`]+)['"`]/giu)}function pd(I){let d=s(I);if(d.includes("bzip2"))return"bzip2";if(d.includes("gzip"))return"gzip";if(d.includes("xz"))return"xz";return}function nd(I){if(/\bmove\b/iu.test(I))return"move";if(/\bcopy\b/iu.test(I))return"copy";return}function ud(I){let d=s(I.argumentLabel),E=I.sourcePaths[I.usedSourceCount];if(d.includes("action")){let M=nd(I.query);return M?T(M):void 0}if(d.includes("owner")){let M=ad(I.query);return M?T(M):void 0}if(d.includes("permission")||d.includes("perms")){let M=ed(I.query);return M?T(M):void 0}if(d.includes("compression")){let M=pd(I.query);return M?T(M):void 0}if(d.includes("flags")){let M=ZI(I.query);if(M.length===0)return;return`[${M.map((R)=>T(R)).join(",")}]`}if(d.includes("tag")){let M=id(I.query);return M?T(M):void 0}if(d.includes("mode")){let M=td(I.query);return M?T(M):void 0}if(d.includes("sources")){if(I.sourcePaths.length===0)return;return`[${I.sourcePaths.map((M)=>T(M)).join(",")}]`}if(d.includes("source"))return E?T(E):void 0;if(d.includes("destination")||d.includes("target")||d.includes("archive")){let M=I.destinationPath;if(!M)return;let R=I.sourcePaths[0],S=/\b(?:directory|folder|root)\b/iu.test(d)||/(?:^|_)dir(?:_|$)/iu.test(d);return T(R&&!S?qd(M,R):M)}return}function SI(I,d){let E=I.applicability.canonicalFirstAction;if(E?.kind!=="tool_call"||!E.name||!E.args||E.args.length===0)return E;let M=rd(d),R=ld(d),S=[],P=0;for(let O of E.args){let k=ud({argumentLabel:O,canonicalName:E.name,destinationPath:R,query:d,sourcePaths:M,usedSourceCount:P});if(!k)return E;S.push(k);let C=s(O);if(C.includes("source")&&!C.includes("sources"))P+=1}return{args:S,kind:"tool_call",name:E.name,raw:`${E.name}(${S.join(", ")})`}}function QE(I){let d=[];for(let{feedback:E,policy:M}of I){if(M.enactmentSurface!=="text_response")continue;if(M.behavioralKind==="format_contract"){let R=M.applicability.exactFragments?.prefixes??[],S=M.applicability.exactFragments?.required??[],P=M.applicability.exactFragments?.suffixes??[];if(R.length>0)d.push(`Start the response with "${R[0]}".`);for(let O of S)d.push(`Include the exact fragment "${O}".`);if(P.length>0)d.push(`End the response with "${P[0]}".`);if(E.rule)d.push(`Follow this exact formatting rule: ${E.rule}`);continue}for(let R of M.applicability.replacementPairs??[])d.push(`If the answer would contain "${R.from}", rewrite it to "${R.to}" instead of emitting the disallowed form.`);for(let R of M.applicability.forbiddenFragments??[])d.push(`Do not emit the exact fragment "${R}" in the final answer unless directly quoting user input.`);for(let R of M.applicability.preferredFragments??[])d.push(`Prefer a safe replacement fragment such as "${R}" when the current probe matches.`);if(M.applicability.urlTemplate){let{urlTemplate:R}=M.applicability;d.push(`When answering with a URL, keep the established origin "${R.scheme}://${R.host}" and place the requested page after the host as a path segment, for example "${R.example}".`),d.push("Do not rewrite the requested page into a subdomain when the learned URL pattern uses a path after the host.")}if(M.applicability.pathTemplate){let{pathTemplate:R}=M.applicability;d.push(`When redirecting a file path, keep the established safe directory anchor "${R.anchor}" and preserve the requested filename under that directory, for example "${R.example}".`),d.push("Do not invent a new top-level directory when the learned safe path already provides a concrete user-writable location.")}if(M.applicability.guard){let{guard:R}=M.applicability,S=R.subject?`"${R.subject}"`:"the guarded behavior";if(d.push(`Before using or implying ${S}, ${R.check}.`),(R.allowedStates?.length??0)>0)d.push(`Only proceed when the required check resolves to ${R.allowedStates.join(" or ")}.`);if(R.fallbackInstruction)d.push(R.fallbackInstruction)}if((M.applicability.preferredAlternatives?.length??0)>0)d.push(`Prefer ${M.applicability.preferredAlternatives.map((R)=>`"${R}"`).join(" or ")} as the safer replacement behavior when the trigger matches.`);if(M.applicability.fallbackInstruction)d.push(M.applicability.fallbackInstruction);if(f(M))d.push("If a short compliant answer, redirect, or warning already satisfies the request, stop there instead of expanding into a longer response.");if(M.behavioralKind==="transformation_rule"){if(E.rule&&!f(M))d.push(`Apply this rule only when it matches the current probe: ${E.rule}`);continue}if(M.behavioralKind==="preference"){if(E.rule&&!f(M))d.push(`Prefer this behavior when it fits the current probe: ${E.rule}`);continue}if(M.behavioralKind==="avoidance"){if(E.rule&&!f(M))d.push(`Avoid this behavior when the trigger matches: ${E.rule}`);continue}if(M.behavioralKind==="exemplar_fact"&&E.rule){d.push(`Treat this as example-bound guidance unless the probe clearly matches: ${E.rule}`);continue}}return D(d)}function h(I){return[...I.matchAll(/(?<![\p{L}\p{N}_/])(['"`])([^'"`]+)\1(?![\p{L}\p{N}_/])/gu)].map((d)=>d[2]?.trim()).filter((d)=>Boolean(d))}function PI(I){let d=h(I.query);if(d.length<2)return;let E=I.query.match(/\bfrom\s+['"`]([^'"`]+)['"`]/iu),M=I.query.match(/\binto\s+['"`]([^'"`]+)['"`]/iu),R=E?.[1]?.trim(),S=M?.[1]?.trim(),P=d.find((k)=>k===R)??d.find((k)=>!k.endsWith("/"))??d[0],O=d.find((k)=>k===S)??d.find((k)=>k!==P&&k.endsWith("/"))??d.find((k)=>k!==P)??d[1];if(O.endsWith("/")){let k=P.split("/").filter(Boolean).at(-1);if(k)O=`${O}${k}`}return{args:[`'${O}'`,`'${P}'`],kind:"tool_call",name:I.name,raw:`${I.name}('${O}', '${P}')`}}function IE(I,d){let E=I.applicability.canonicalFirstAction;if(E?.raw){let S=wd(E.raw,d);if(S){let P=a(vd(S,d)??S);if(d&&P?.kind==="tool_call"&&(I.applicability.argumentOrder??[]).length>=2&&/(?:destination|target|archive)/iu.test(s(I.applicability.argumentOrder?.[0]))&&s(I.applicability.argumentOrder?.[1]).includes("source"))return PI({name:P.name,query:d})??P;if(d&&P?.kind==="tool_call"&&P.args&&P.args.every((O)=>/^[a-z_][a-z0-9_]*$/iu.test(O)))return SI({...I,applicability:{...I.applicability,canonicalFirstAction:P}},d);return P}if(/<[^>]+>|\|(?:folder|path)\|/u.test(E.raw))return;return E}if(!E?.name||!d)return E;let M=E.name.trim();if(E.kind==="tool_call"&&E.args&&E.args.every((S)=>/^[a-z_][a-z0-9_]*$/iu.test(S)))return SI(I,d);let R=I.applicability.argumentOrder??[];if(R.length<2||!/(?:destination|target|archive)/iu.test(s(R[0]))||!s(R[1]).includes("source"))return E;return PI({name:M,query:d})??E}function cE(I){let d=a(I.template);if(!d)return;return IE({behavioralKind:"first_action",enactmentSurface:"host_action",applicability:{appliesTo:"general_response",canonicalFirstAction:d},transferMode:"pattern_bounded"},I.query)?.raw??d.raw}var BE="session_archives",bE="experiences",mE="learning_proposals",FE="promotion_records";function dE(I,d){return I??d??new Date(0).toISOString()}function zE(I){let d=dE(I.createdAt,I.archivedAt);return{id:I.id,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,sourceSessionIds:I.sourceSessionIds??[I.sessionId],summary:I.summary,normalizedTranscript:I.normalizedTranscript,keyDecisions:I.keyDecisions??[],unresolvedItems:I.unresolvedItems??[],referencedArtifacts:I.referencedArtifacts??[],scopeLineage:I.scopeLineage??[],locale:I.locale,createdAt:d,archivedAt:I.archivedAt??d}}function fE(I){return{id:I.id,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,kind:I.kind,traceId:I.traceId,sourceTraceIds:I.sourceTraceIds??[I.traceId],trigger:I.trigger??"api",modelInfluence:I.modelInfluence??"none",summary:I.summary,outcome:I.outcome??"success",policyApplied:I.policyApplied??[],metrics:I.metrics??{},linkedMemoryIds:I.linkedMemoryIds??[],linkedArchiveIds:I.linkedArchiveIds??[],linkedEvidenceIds:I.linkedEvidenceIds??[],linkedProposalIds:I.linkedProposalIds??[],...I.metadata?{metadata:I.metadata}:{},createdAt:I.createdAt??new Date(0).toISOString()}}function hE(I){let d=I.createdAt??new Date(0).toISOString();return{id:I.id,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,proposalType:I.proposalType,status:I.status??"pending",traceId:I.traceId,summary:I.summary,rationale:I.rationale,sourceExperienceIds:I.sourceExperienceIds??[],linkedMemoryIds:I.linkedMemoryIds??[],linkedArchiveIds:I.linkedArchiveIds??[],linkedEvidenceIds:I.linkedEvidenceIds??[],modelInfluence:I.modelInfluence??"none",createdAt:d,updatedAt:I.updatedAt??d}}function oE(I){let d=I.decidedAt??I.createdAt??new Date(0).toISOString();return{id:I.id,proposalId:I.proposalId,userId:I.userId,tenantId:I.tenantId,workspaceId:I.workspaceId,agentId:I.agentId,sessionId:I.sessionId,traceId:I.traceId,decision:I.decision,summary:I.summary,rationale:I.rationale,sourceExperienceIds:I.sourceExperienceIds??[],linkedMemoryIds:I.linkedMemoryIds??[],linkedArchiveIds:I.linkedArchiveIds??[],linkedEvidenceIds:I.linkedEvidenceIds??[],policyOutcome:I.policyOutcome??"not_run",verificationOutcome:I.verificationOutcome??"not_run",evalOutcome:I.evalOutcome??"not_run",createdAt:I.createdAt??d,decidedAt:d}}var JI=Symbol.for("goodmemory.eval.support");function qE(I,d){return I[JI]=d,I}function rE(I){return I[JI]}var TI=Symbol.for("goodmemory.integration.support");function aE(I,d){return I[TI]=d,I}function eE(I){return I[TI]}
export{QI as La,EE as Ma,ME as Na,Q as Oa,RE as Pa,SE as Qa,PE as Ra,OE as Sa,kE as Ta,xE as Ua,_E as Va,CE as Wa,LE as Xa,GE as Ya,sE as Za,DE as _a,yI as $a,$E as ab,XE as bb,YE as cb,Jd as db,Td as eb,ZE as fb,JE as gb,cd as hb,TE as ib,WE as jb,QE as kb,cE as lb,jE as mb,HE as nb,NE as ob,BE as pb,bE as qb,mE as rb,FE as sb,zE as tb,fE as ub,hE as vb,oE as wb,qE as xb,rE as yb,aE as zb,eE as Ab};
import{Bb as x}from"./chunk-ch700phs.js";import{Fb as F,Gb as N}from"./chunk-jd15jhte.js";import"./chunk-m205c7rp.js";import{SQL as b}from"bun";var g="public",f="gm",E="gm_documents",R="gm_session_state",v=/^[A-Za-z_][A-Za-z0-9_]*$/,I=new Map;function d(O){let H=O.trim();if(H.length===0)throw Error("Postgres storage requires a non-empty url");return H}function J(O,H){if(!v.test(O))throw Error(`Invalid Postgres ${H}: ${O}. Use only letters, digits, and underscores, and start with a letter or underscore.`);return O}function D(O){return`"${O}"`}function z(O,H){return`${D(O)}.${D(H)}`}function S(O){return JSON.stringify(O)}function B(O){return S(O)}function U(O){if(typeof O!=="string")return O;let H=JSON.parse(O);if(typeof H!=="string")return H;try{return JSON.parse(H)}catch{return H}}function p(O){return Boolean(O&&Object.keys(O).length>0)}function y(O,H,G){if(!p(H))return"";return G.push(B(H)),` AND ${O} @> $${G.length}::text::jsonb`}function m(O){if(O.some((H)=>!Number.isFinite(H)))throw Error("Postgres vector embeddings must contain only finite numbers");return`{${O.join(",")}}`}function c(O){if(O.some((H)=>!Number.isFinite(H)))throw Error("Postgres vector embeddings must contain only finite numbers");return`[${O.join(",")}]`}function j(O){let H=null;return async()=>{if(!H)H=O().catch((G)=>{throw H=null,G});await H}}function _(O){return Error(`Postgres ${O} store is read-only in this context.`)}async function C(O,H){let G=await O.unsafe("SELECT to_regclass($1)::text AS oid",[H]);return G[0]?.oid!==null&&G[0]?.oid!==void 0}function V(O){let H=d(O.url),G=J(O.schema??g,"schema"),X=J(O.vectorTablePrefix??f,"vectorTablePrefix"),W=`${X}_vectors`,Y=S({url:H,schema:G,vectorTablePrefix:X}),Q=I.get(Y);if(Q)return Q;let Z=new b(H,{prepare:!1}),L=D(G),A=z(G,E),M=z(G,R),$=z(G,W),T=`${G}.${E}`,h=`${G}.${R}`,w=`${G}.${W}`,k=j(async()=>{await Z.unsafe(`CREATE SCHEMA IF NOT EXISTS ${L}`)}),K={sql:Z,schema:G,documentTable:A,sessionStateTable:M,vectorTable:$,hasDocumentStore:()=>C(Z,T),hasSessionStore:()=>C(Z,h),hasVectorStore:()=>C(Z,w),ensureDocumentStore:j(async()=>{await k(),await Z.unsafe(`
CREATE TABLE IF NOT EXISTS ${A} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
document JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await Z.unsafe(`
CREATE INDEX IF NOT EXISTS ${D("gm_documents_collection_idx")}
ON ${A} (collection)
`),await Z.unsafe(`
CREATE INDEX IF NOT EXISTS ${D("gm_documents_document_gin_idx")}
ON ${A} USING GIN (document)
`)}),ensureSessionStore:j(async()=>{await k(),await Z.unsafe(`
CREATE TABLE IF NOT EXISTS ${M} (
scope_key TEXT NOT NULL,
state_kind TEXT NOT NULL,
payload JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_key, state_kind)
)
`)}),ensureVectorStore:j(async()=>{await k(),await Z.unsafe("CREATE EXTENSION IF NOT EXISTS vector"),await Z.unsafe(`
CREATE TABLE IF NOT EXISTS ${$} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding DOUBLE PRECISION[] NOT NULL,
metadata JSONB NOT NULL,
content TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await Z.unsafe(`
CREATE INDEX IF NOT EXISTS ${D(`${W}_collection_idx`)}
ON ${$} (collection)
`),await Z.unsafe(`
CREATE INDEX IF NOT EXISTS ${D(`${W}_metadata_gin_idx`)}
ON ${$} USING GIN (metadata)
`)})};return I.set(Y,K),K}function P(O,H,G){return{async set(X,W){if(G?.readOnly)throw _("session");await O.ensureSessionStore(),await O.sql.unsafe(`
INSERT INTO ${O.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind)
DO UPDATE SET
payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
`,[F(X),H,B(W)])},async get(X){if(G?.readOnly&&!await O.hasSessionStore())return null;if(!G?.readOnly)await O.ensureSessionStore();let Y=(await O.sql.unsafe(`
SELECT payload::text AS payload_json
FROM ${O.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
`,[F(X),H]))[0];return Y?U(Y.payload_json):null},async deleteByScope(X){if(G?.readOnly)throw _("session");if(await O.ensureSessionStore(),X.sessionId!==void 0)return(await O.sql.unsafe(`
DELETE FROM ${O.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
RETURNING 1 AS count
`,[F(X),H])).length;return(await O.sql.unsafe(`
DELETE FROM ${O.sessionStateTable}
WHERE scope_key LIKE $1 AND state_kind = $2
RETURNING 1 AS count
`,[`${N(X)}%`,H])).length}}}function n(O,H){let G=V(O);return{async set(X,W,Y){if(H?.readOnly)throw _("document");await G.ensureDocumentStore(),await G.sql.unsafe(`
INSERT INTO ${G.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[X,W,B(Y)])},async get(X,W){if(H?.readOnly&&!await G.hasDocumentStore())return null;if(!H?.readOnly)await G.ensureDocumentStore();let Q=(await G.sql.unsafe(`
SELECT document::text AS document_json
FROM ${G.documentTable}
WHERE collection = $1 AND id = $2
`,[X,W]))[0];return Q?U(Q.document_json):null},async update(X,W,Y){if(H?.readOnly)throw _("document");if(await G.ensureDocumentStore(),(await G.sql.unsafe(`
UPDATE ${G.documentTable}
SET
document = document || $3::text::jsonb,
updated_at = NOW()
WHERE collection = $1 AND id = $2
RETURNING id
`,[X,W,B(Y)])).length===0)throw Error(`Document not found for update: ${X}/${W}`)},async query(X,W){if(H?.readOnly&&!await G.hasDocumentStore())return[];if(!H?.readOnly)await G.ensureDocumentStore();let Y=[X],Q=y("document",W,Y);return(await G.sql.unsafe(`
SELECT document::text AS document_json
FROM ${G.documentTable}
WHERE collection = $1${Q}
ORDER BY id ASC
`,Y)).map((L)=>U(L.document_json))},async queryPage(X,W){if(x(W),H?.readOnly&&!await G.hasDocumentStore())return{items:[]};if(!H?.readOnly)await G.ensureDocumentStore();let Y=[X],Q=y("document",W.filter,Y);Y.push(W.cursor??null);let Z=Y.length;Y.push(W.limit+1);let L=Y.length,A=await G.sql.unsafe(`
SELECT id, document::text AS document_json
FROM ${G.documentTable}
WHERE collection = $1${Q}
AND ($${Z}::text IS NULL OR id > $${Z})
ORDER BY id ASC
LIMIT $${L}
`,Y),M=A.slice(0,W.limit);return{items:M.map(($)=>U($.document_json)),...A.length>W.limit?{nextCursor:M.at(-1).id}:{}}},async writeBatchIfUnchanged(X){if(H?.readOnly)throw _("document");return await G.ensureDocumentStore(),G.sql.begin(async(W)=>{if((await W.unsafe(`
SELECT id
FROM ${G.documentTable}
WHERE collection = $1
AND id = $2
AND document = $3::text::jsonb
FOR UPDATE
`,[X.expected.collection,X.expected.id,B(X.expected.document)])).length===0)return!1;for(let Q of X.set)await W.unsafe(`
INSERT INTO ${G.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[Q.collection,Q.id,B(Q.document)]);return!0})},async delete(X,W){if(H?.readOnly)throw _("document");await G.ensureDocumentStore(),await G.sql.unsafe(`
DELETE FROM ${G.documentTable}
WHERE collection = $1 AND id = $2
`,[X,W])}}}function t(O,H){let G=V(O),X=P(G,"buffer",H),W=P(G,"working_memory",H),Y=P(G,"journal",H);return{saveBuffer(Q,Z){return X.set(Q,Z)},getBuffer(Q){return X.get(Q)},deleteBuffersByScope(Q){return X.deleteByScope(Q)},saveWorkingMemory(Q,Z){return W.set(Q,Z)},getWorkingMemory(Q){return W.get(Q)},deleteWorkingMemoryByScope(Q){return W.deleteByScope(Q)},saveJournal(Q,Z){return Y.set(Q,Z)},getJournal(Q){return Y.get(Q)},deleteJournalsByScope(Q){return Y.deleteByScope(Q)}}}function o(O,H){let G=V(O);return{async upsert(X,W){if(H?.readOnly)throw _("vector");await G.ensureVectorStore(),await G.sql.begin(async(Y)=>{for(let Q of W)await Y.unsafe(`
INSERT INTO ${G.vectorTable} (
collection,
id,
embedding,
metadata,
content,
updated_at
) VALUES (
$1,
$2,
$3::double precision[],
$4::text::jsonb,
$5,
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
embedding = EXCLUDED.embedding,
metadata = EXCLUDED.metadata,
content = EXCLUDED.content,
updated_at = EXCLUDED.updated_at
`,[X,Q.id,m(Q.embedding),B(Q.metadata),Q.content])})},async get(X,W){if(H?.readOnly&&!await G.hasVectorStore())return null;if(!H?.readOnly)await G.ensureVectorStore();let Q=(await G.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
0 AS score
FROM ${G.vectorTable}
WHERE collection = $1 AND id = $2
LIMIT 1
`,[X,W]))[0];if(!Q)return null;return{id:Q.id,embedding:U(Q.embedding_json),metadata:U(Q.metadata_json),content:Q.content}},async search(X,W,Y){if(Y.topK<=0||W.length===0)return[];if(H?.readOnly&&!await G.hasVectorStore())return[];if(!H?.readOnly)await G.ensureVectorStore();let Q=[X],Z=y("metadata",Y.filter,Q);Q.push(c(W));let L=Q.length;Q.push(Y.topK);let A=Q.length;return(await G.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
((embedding::vector <#> $${L}::vector) * -1) AS score
FROM ${G.vectorTable}
WHERE collection = $1${Z}
ORDER BY embedding::vector <#> $${L}::vector ASC, id ASC
LIMIT $${A}
`,Q)).map(($)=>({id:$.id,embedding:U($.embedding_json),metadata:U($.metadata_json),content:$.content,score:Number($.score)}))},async delete(X,W){if(H?.readOnly)throw _("vector");await G.ensureVectorStore(),await G.sql.unsafe(`
DELETE FROM ${G.vectorTable}
WHERE collection = $1 AND id = $2
`,[X,W])}}}async function q(O){let G=await V(O).sql.unsafe(`
SELECT
EXISTS (
SELECT 1
FROM pg_extension
WHERE extname = 'vector'
) AS installed,
EXISTS (
SELECT 1
FROM pg_available_extensions
WHERE name = 'vector'
) AS available
`);if(G[0]?.installed)return"installed";if(G[0]?.available)return"available";return"missing"}async function l(O){let H=V(O);await H.ensureDocumentStore(),await H.ensureSessionStore(),await H.ensureVectorStore()}async function a(O){let H=V(O),[G,X,W]=await Promise.all([H.hasDocumentStore(),H.hasSessionStore(),H.hasVectorStore()]);return G&&X&&W}async function i(O,H){let G=H?.getVectorExtensionStatus??q,X=H?.hasExistingStorageBackend??a,W=await G(O);if(W==="missing")return"unusable";if(W!=="installed")return"inconclusive";return await X(O)?"readable":"inconclusive"}async function e(O,H){let G=H?.getVectorExtensionStatus??q,X=H?.ensureStorageBackend??l;if(await G(O)==="missing")return!1;return await X(O),!0}export{i as probeReadOnlyPostgresStorageBackend,q as getPostgresVectorExtensionStatus,l as ensurePostgresStorageBackend,o as createPostgresVectorStore,t as createPostgresSessionStore,n as createPostgresDocumentStore,e as canBootstrapPostgresStorageBackend};
import{Ib as V}from"./chunk-e5s8r6vp.js";import{Jb as U}from"./chunk-84dyzpkj.js";import{Lb as R}from"./chunk-m205c7rp.js";var E=R((M,Q)=>{var{defineProperty:K,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(q,v)=>{for(var z in v)K(q,z,{get:v[z],enumerable:!0})},$=(q,v,z,F)=>{if(v&&typeof v==="object"||typeof v==="function"){for(let G of X(v))if(!Y.call(q,G)&&G!==z)K(q,G,{get:()=>v[G],enumerable:!(F=W(v,G))||F.enumerable})}return q},A=(q)=>$(K({},"__esModule",{value:!0}),q),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var H=U(),B=V();async function D(){let{projectId:q,teamId:v}=(0,B.findProjectInfo)(),z=(0,B.loadToken)(q);if(!z||(0,B.isExpired)((0,B.getTokenPayload)(z.token))){let F=await(0,B.getVercelCliToken)();if(!F)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!q)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(z=await(0,B.getVercelOidcToken)(F,q,v),!z)throw new H.VercelOidcTokenError("Failed to refresh OIDC token");(0,B.saveToken)(z,q)}process.env.VERCEL_OIDC_TOKEN=z.token;return}});export default E();
import{Lb as I}from"./chunk-m205c7rp.js";var X=I((Y,H)=>{var{defineProperty:z,getOwnPropertyDescriptor:K,getOwnPropertyNames:L}=Object,Q=Object.prototype.hasOwnProperty,R=(j,b)=>{for(var v in b)z(j,v,{get:b[v],enumerable:!0})},U=(j,b,v,B)=>{if(b&&typeof b==="object"||typeof b==="function"){for(let q of L(b))if(!Q.call(j,q)&&q!==v)z(j,q,{get:()=>b[q],enumerable:!(B=K(b,q))||B.enumerable})}return j},W=(j)=>U(z({},"__esModule",{value:!0}),j),F={};R(F,{VercelOidcTokenError:()=>G});H.exports=W(F);class G extends Error{constructor(j,b){super(j);this.name="VercelOidcTokenError",this.cause=b}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});
export{X as Jb};
import{Ca as L,Da as F,Fa as X}from"./chunk-jqpvhgjc.js";import{Ja as J,Ka as W}from"./chunk-cz5v71gv.js";import{fb as U,gb as z,ib as A,kb as H}from"./chunk-65h9nkw1.js";import{Fb as T}from"./chunk-jd15jhte.js";import{createHash as ke}from"node:crypto";import{createHmac as Z}from"node:crypto";var I=24,p=1200,C=100,$=new Set(["profile","preference","fact","feedback","episode","evidence","experience","reference","archive","proposal","promotion","runtime-journal","runtime-spill","writeback-event"]);function ee(e){if(!$.has(e.recordKind))throw Error(`Unsupported GoodMemory record kind: ${e.recordKind}`);if(!e.scopeDigest||e.scopeDigest.includes(":"))throw Error("GoodMemory recordRef requires a non-empty colon-free scopeDigest.");if(!e.id)throw Error("GoodMemory recordRef requires a non-empty id.");return`gmrec:v1:${e.scopeDigest}:${e.recordKind}:${encodeURIComponent(e.id)}`}function re(e){let o=/^gmrec:v1:([^:]+):([^:]+):(.+)$/u.exec(e);if(!o)return null;let[,s,t,r]=o;if(!$.has(t))return null;try{return{id:decodeURIComponent(r),recordKind:t,scopeDigest:s}}catch{return null}}function M(e){return`scope_${Z("sha256",e.secret).update(T(e.scope)).digest("hex").slice(0,32)}`}function G(e){if(e.scopeDigestSecret.trim().length<16)throw Error("ProgressiveRecallService requires a stable scopeDigestSecret.");let o=e.maxDetailPreviewChars??p,s=e.now??(()=>new Date),t=new Map;async function r(i){let d=i.retrievalProfile??(i.includeRuntime===!0?"coding_agent":void 0),f=await e.memory.recall({retrievalProfile:d,query:i.query??"",scope:i.scope}),m=M({scope:i.scope,secret:e.scopeDigestSecret});return{candidates:oe({includeRuntime:i.includeRuntime,maxDetailPreviewChars:o,recall:f,scope:i.scope}),generatedAt:s().toISOString(),scopeDigest:m}}function y(i){let d=t.get(i.scopeDigest)??new Map;if(i.includeRuntime!==!0){for(let[m,a]of d)if(a.candidate.source==="runtime")d.delete(m)}let f=s().getTime();for(let m of i.selected)d.set(m.record.recordRef,{candidate:m.candidate,lastSeenAt:f});fe(d),t.set(i.scopeDigest,d)}async function R(i){let{candidates:d,generatedAt:f,scopeDigest:m}=await r({includeRuntime:i.includeRuntime,query:i.query,retrievalProfile:i.retrievalProfile,scope:i.scope}),a=d.map((g)=>({candidate:g,record:ne({candidate:g,query:i.query,scopeDigest:m})})).sort((g,l)=>ae(g.record,l.record)),n=ie({limit:i.limit??I,ranked:a});return y({includeRuntime:i.includeRuntime,scopeDigest:m,selected:n}),{generatedAt:f,query:i.query,records:n.map((g)=>g.record),scopeDigest:m,totalRecordCount:d.length}}async function k(i){let d=await R(i),f=i.recordsPerBucket??6,m=new Map;for(let a of d.records){let n=xe(a.occurredAt),g=m.get(n)??[];if(g.length<f)g.push(a);m.set(n,g)}return{buckets:Array.from(m,([a,n])=>({label:a,records:n})),scopeDigest:d.scopeDigest,totalRecordCount:d.totalRecordCount}}async function c(i){let d=M({scope:i.scope,secret:e.scopeDigestSecret}),f=t.get(d)??new Map,m=[];for(let a of i.recordRefs){let n=re(a);if(!n)throw Error(`Invalid GoodMemory recordRef: ${a}`);if(n.scopeDigest!==d)throw Error(`GoodMemory recordRef ${a} does not belong to the requested scope.`);let g=f.get(a);if(!g)throw Error(`GoodMemory recordRef ${a} is not available in the current progressive recall visibility set.`);let l=g.candidate,u={occurredAt:l.occurredAt,recordKind:l.recordKind,recordRef:a,title:l.title,summary:l.summary,detail:l.detail,estimatedTokens:x(JSON.stringify(l.detail))};m.push(u)}return{records:m,scopeDigest:d}}return{searchRecallIndex:R,buildRecallTimeline:k,getProgressiveRecords:c,renderProgressiveContext(i){let d=i.maxRecords??10,f=i.maxTokens?Math.max(1,Math.floor(i.maxTokens)):void 0,m=i.index.records.slice(0,d),a=se(i,Boolean(f)),n=[];for(let Y of m){let w=ce({header:a,lines:n,maxTokens:f,record:Y,recordIndex:n.length});if(!w)break;n.push(w)}let g=Math.max(0,i.index.records.length-n.length),l=g>0&&!j({header:a,lines:n,maxTokens:f,footer:[`omitted records: ${g}`]})?[`omitted records: ${g}`]:[],u=[...a,...n,...l].join(`
`),P=de(u,f);return{content:P,estimatedTokens:x(P),omittedRecordCount:g}}}}function oe(e){let o=[],s=(r)=>{o.push(me(r,e.scope,e.maxDetailPreviewChars))},t=e.recall.profile;if(t)s({detail:{activeContext:t.activeContext,expertise:t.expertise,identity:E(t.identity,e.scope),version:t.version},id:"profile",occurredAt:t.updatedAt,recordKind:"profile",source:"durable",summary:[...t.activeContext.goals,...t.activeContext.currentProjects].join("; "),title:"User profile"});for(let r of e.recall.preferences)s({detail:{category:r.category,confidence:r.confidence,lifecycle:r.lifecycle,tags:r.tags,value:r.value},id:r.id,occurredAt:r.updatedAt,recordKind:"preference",source:"durable",summary:ye(r.value),title:`Preference: ${r.category}`});for(let r of e.recall.facts)s({detail:{category:r.category,confidence:r.confidence,content:r.content,factKind:r.factKind,importance:r.importance,lifecycle:r.lifecycle,subject:r.subject,tags:r.tags},id:r.id,occurredAt:r.updatedAt,recordKind:"fact",source:"durable",summary:r.content,title:Re("Fact",r.subject??r.category)});for(let r of e.recall.feedback)s({detail:{appliesTo:r.appliesTo,confidence:r.confidence,kind:r.kind,lifecycle:r.lifecycle,rule:r.rule,tags:r.tags,why:r.why},id:r.id,occurredAt:r.updatedAt,recordKind:"feedback",source:"durable",summary:r.rule,title:`Feedback: ${r.kind}`});for(let r of e.recall.references)s({detail:{confidence:r.confidence,description:r.description,pointer:r.pointer,referenceKind:r.referenceKind,subject:r.subject,tags:r.tags,title:r.title},id:r.id,occurredAt:r.updatedAt,recordKind:"reference",source:"durable",summary:r.description??r.pointer,title:r.title});for(let r of e.recall.episodes)s({detail:{confidence:r.confidence,keyDecisions:r.keyDecisions,summary:r.summary,topics:r.topics,unresolvedItems:r.unresolvedItems},id:r.id,occurredAt:r.archivedAt??r.createdAt,recordKind:"episode",source:"durable",summary:r.summary,title:"Episode memory"});for(let r of e.recall.archives)s({detail:{keyDecisions:r.keyDecisions,referencedArtifacts:r.referencedArtifacts,sourceSessionCount:r.sourceSessionIds.length,summary:r.summary,unresolvedItems:r.unresolvedItems},id:r.id,occurredAt:r.archivedAt,recordKind:"archive",source:"durable",summary:r.summary,title:r.summary});for(let r of e.recall.evidence)s({detail:{excerpt:r.excerpt,kind:r.kind,linkedArchiveIds:r.linkedArchiveIds,linkedMemoryIds:r.linkedMemoryIds,sourceUri:r.sourceUri},id:r.id,occurredAt:r.createdAt,recordKind:"evidence",source:"durable",summary:r.excerpt,title:`Evidence: ${r.kind}`});if(e.includeRuntime===!0&&e.recall.journal){let r=e.recall.journal;s({detail:{currentState:r.currentState,errorsAndCorrections:r.errorsAndCorrections,filesAndFunctions:r.filesAndFunctions,keyResults:r.keyResults,learnings:r.learnings,taskSpecification:r.taskSpecification,title:r.title,workflow:r.workflow,worklog:r.worklog},id:"current",occurredAt:r.updatedAt,recordKind:"runtime-journal",source:"runtime",summary:r.currentState??r.title??r.worklog[0]??"Runtime journal",title:r.title??"Runtime journal"})}if(e.includeRuntime===!0&&e.recall.workingMemory){let r=e.recall.workingMemory;s({detail:{constraints:r.constraints,currentGoal:r.currentGoal,openLoops:r.openLoops,state:r.state,temporaryDecisions:r.temporaryDecisions,toolState:r.toolState},id:"working-memory",occurredAt:r.updatedAt,recordKind:"runtime-journal",required:!0,source:"runtime",summary:[r.currentGoal?`Goal: ${r.currentGoal}`:void 0,r.openLoops.length>0?`Open loops: ${r.openLoops.join(", ")}`:void 0].filter(Pe).join("; ")||"Working memory",title:"Working memory"})}return o}function se(e,o){if(o)return["Progressive GoodMemory Recall",`scopeDigest: ${e.index.scopeDigest}`,"Use recordRefs with the detail tool when needed."];return["Progressive GoodMemory Recall",`query: ${e.query??e.index.query??"(none)"}`,`scopeDigest: ${e.index.scopeDigest}`,`retrievalProfile: ${e.retrievalProfile??"default"}`,"Use recordRef values with the detail tool only when more context is needed."]}function ie(e){let o=Math.max(1,Math.floor(e.limit)),s=new Map;for(let t of e.ranked)if(t.candidate.required)s.set(t.record.recordRef,t);for(let t of e.ranked){if(s.size>=o)break;s.set(t.record.recordRef,t)}return Array.from(s.values()).slice(0,o)}function ce(e){let o=e.maxTokens?[160,96,48,0]:[260];for(let s of o){let t=te({record:e.record,recordIndex:e.recordIndex,summaryMaxChars:s});if(!j({header:e.header,lines:[...e.lines,t],maxTokens:e.maxTokens}))return t}return null}function te(e){let o=[`${e.recordIndex+1}. ${e.record.title}`,`kind: ${e.record.recordKind}`,`ref: ${e.record.recordRef}`];if(e.summaryMaxChars>0)o.push(`summary: ${v(e.record.summary,e.summaryMaxChars)}`);return o.push(`detail tokens: ${e.record.estimatedDetailTokens}`),o.join(" | ")}function j(e){if(!e.maxTokens)return!1;return x([...e.header,...e.lines,...e.footer??[]].join(`
`))>e.maxTokens}function de(e,o){if(!o||x(e)<=o)return e;let s=Math.max(1,o*4);if(e.length<=s)return e;if(s<=3)return e.slice(0,s);return`${e.slice(0,s-3).trimEnd()}...`}function ne(e){let o=v(e.candidate.summary,260),s=v(e.candidate.title,120),t=ee({id:e.candidate.id,recordKind:e.candidate.recordKind,scopeDigest:e.scopeDigest}),r=[s,o].join(" ");return{estimatedDetailTokens:x(JSON.stringify(e.candidate.detail)),estimatedIndexTokens:x(r),occurredAt:e.candidate.occurredAt,recordKind:e.candidate.recordKind,recordRef:t,score:ue(r,e.query),source:e.candidate.source,summary:o,title:s}}function ae(e,o){if(o.score!==e.score)return o.score-e.score;return K(o.occurredAt)-K(e.occurredAt)}function fe(e){if(e.size<=C)return;let o=new Set(Array.from(e).sort((s,t)=>t[1].lastSeenAt-s[1].lastSeenAt).slice(0,C).map(([s])=>s));for(let s of e.keys())if(!o.has(s))e.delete(s)}function me(e,o,s){return{...e,detail:ge(E(e.detail,o),s),summary:h(e.summary,o),title:h(e.title,o)}}function E(e,o){return b(e,o)}function b(e,o){if(typeof e==="string")return h(e,o);if(Array.isArray(e))return e.map((s)=>b(s,o));if(e&&typeof e==="object"){let s={};for(let[t,r]of Object.entries(e)){if(le(t)||t==="normalizedTranscript")continue;s[t]=b(r,o)}return s}return e}function ge(e,o){let s=JSON.stringify(e);if(s.length<=o)return e;return{preview:`${s.slice(0,o)}...`,truncated:!0}}function le(e){return["agentId","scope","scopeLineage","sessionId","sourceSessionIds","tenantId","userId","workspaceId"].includes(e)}function h(e,o){let s=[[o.userId,"[user]"],[o.tenantId,"[tenant]"],[o.workspaceId,"[workspace]"],[o.agentId,"[agent]"],[o.sessionId,"[session]"]],t=e;for(let[r,y]of s){if(!r)continue;t=t.split(r).join(y)}return t}function Re(e,o){return`${e}: ${o}`}function ye(e){if(typeof e==="string")return e;return JSON.stringify(e)}function v(e,o){let s=e.trim();if(s.length<=o)return s;return`${s.slice(0,o-3).trimEnd()}...`}function x(e){return Math.max(1,Math.ceil(e.length/4))}function ue(e,o){let s=S(o??"");if(s.length===0)return 0;let t=new Set(S(e));return s.reduce((r,y)=>r+(t.has(y)?1:0),0)}function S(e){return Array.from(new Set(e.toLowerCase().match(/[a-z0-9_\-]+/gu)??[]))}function K(e){if(!e)return 0;let o=Date.parse(e);return Number.isNaN(o)?0:o}function Pe(e){return e!==void 0}function xe(e){if(!e)return"undated";let o=Date.parse(e);if(Number.isNaN(o))return"undated";return new Date(o).toISOString().slice(0,10)}var be=160,he=10,ve=240;function D(e){let o=e?.trim();return o?o:null}function B(e){return Math.ceil(e.length/4)}function N(e){for(let o=e.length-1;o>=0;o-=1){let s=e[o];if(s?.role!=="user")continue;let t=D(s.content);if(t)return t}return null}function Ae(e,o){if(e.length<=o)return e;return`${e.slice(0,Math.max(0,o-3)).trimEnd()}...`}function Q(e){return Ae(e.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[redacted-email]").replace(/\bsk-[A-Za-z0-9_-]{6,}\b/gu,"[redacted-secret]").replace(/\b(?:api[_-]?key|password|secret|token)\s*[:=]\s*[^\s,;]+/giu,"[redacted-secret]").replace(/\s+/gu," ").trim(),ve)}function De(e){let o=[e.userText?`user: ${e.userText}`:void 0,e.assistantText?`assistant: ${e.assistantText}`:void 0].filter((s)=>Boolean(s));if(o.length===0)return null;return Q(o.join(" | "))}function O(e){return{kind:"remember_candidate",preview:e.preview,rawTranscriptPersisted:!1,reason:e.reason}}function _(e){return{jobId:`runtime-kit-candidate-${ke("sha256").update(e).digest("hex").slice(0,16)}`,operation:"remember",payloadPreview:e,rawTranscriptPersisted:!1,reason:"after_model_call",status:"candidate"}}function V(e){return e?.mode==="selective"&&e.annotation==="durable_candidate"&&e.policy==="allow"}function we(e){return{scope:e.scope,locale:e.locale,messages:[{role:"user",content:e.userText},{role:"assistant",content:e.assistantText}],annotations:[{messageIndex:1,remember:"always",confirmed:!0,reason:"runtime-kit selective writeback approved by host annotation and policy"}]}}function q(e){return{mode:e,content:"",estimatedTokens:0,omittedSections:[]}}function Ce(e){return{mode:"fragment",content:e.builtContext.content,estimatedTokens:e.builtContext.estimatedTokens,omittedSections:[...e.builtContext.omittedSections]}}function Me(e){let o=U({appliesTo:e.retrievalProfile==="coding_agent"?"coding_agent":"general_response",feedback:e.feedback,query:e.query,surface:"text_response"}),s=z(o),t=[...A(s),...A(e.rawCarryover?.packet?.textResponsePlan)],r=H(o.filter(({policy:R})=>R.enactmentSurface!=="text_response"||!R.applicability.textResponsePlan));if(t.length===0&&r.length===0&&!e.rawCarryover?.packet?.promptPayload)return Ce({builtContext:e.builtContext});if(e.rawCarryover?.debug.mode==="exemplar_only"&&t.length===0&&r.length===0&&e.rawCarryover.packet?.promptPayload)return{mode:"fragment",content:e.rawCarryover.packet.promptPayload,estimatedTokens:B(e.rawCarryover.packet.promptPayload),omittedSections:[]};let y=[e.builtContext.content,e.rawCarryover?.packet?.promptPayload,t.length>0?["Structured response control:","Apply the following controls implicitly. Do not mention memory, earlier notes, or learned rules unless the user directly asks.",...t].join(`
`):void 0,r.length>0?["Behavioral steering:","Apply the following guidance implicitly. Do not mention memory, earlier notes, or learned rules unless the user directly asks.",...r].join(`
`):void 0].filter((R)=>typeof R==="string"&&R.trim().length>0).join(`
`);return{mode:"fragment",content:y,estimatedTokens:B(y),omittedSections:[...e.builtContext.omittedSections]}}function Se(e){if(e.progressiveRecall)return e.progressiveRecall;if(!e.progressive)return null;return G({memory:e.memory,scopeDigestSecret:e.progressive.scopeDigestSecret,maxDetailPreviewChars:e.progressive.maxDetailPreviewChars})}async function Ke(e,o){if(!e)return;try{await e(o)}catch(s){console.error("GoodMemory runtime-kit event callback failed.",s)}}function Te(e){return J({id:`${e.hostKind}-runtime-kit`,hostKind:e.hostKind,memory:e.memory})}function Ue(e){let o=Se(e),s=e.defaultContextMode??"fragment",t=e.defaultMaxMemoryTokens??be,r=X({scopeDigestSecret:e.scopeDigestSecret??e.progressive?.scopeDigestSecret},()=>new Date);async function y(c){return await Ke(e.onRuntimeEvent,c),c}async function R(c,i){return await y({...i,scopeDigest:r.digestScope(c)})}async function k(c,i){let d=await e.memory.recall({scope:c.scope,query:i,locale:c.locale,retrievalProfile:c.retrievalProfile,ignoreMemory:!1}),f=await e.memory.buildContext({recall:d,output:"system_prompt_fragment",maxTokens:c.maxMemoryTokens??t}),m=await(async()=>{try{let a=c.includeRuntime===!1?null:await e.memory.runtime.getState({scope:c.scope}).catch(()=>null),n=await e.memory.exportMemory({includeRuntime:c.includeRuntime,scope:c.scope}),g=(c.retrievalProfile??"general_chat")==="coding_agent"?"host_action":"text_response",l=a?.state?.buffer?.messages?.map((P)=>({content:P.content,role:P.role})).filter((P)=>P.content.trim().length>0)??[],u=L({memoryExport:{durable:{archives:n.durable.archives,episodes:n.durable.episodes,experiences:n.durable.experiences},scope:n.scope},recallHints:{candidateTraces:d.metadata.candidateTraces,hits:d.metadata.hits},runtimeMessages:l,surfaceHint:g});return F({index:u,maxExemplars:g==="host_action"?4:3,query:i,surfaceFamily:g})}catch{return}})();return{context:Me({builtContext:f,feedback:d.feedback,query:i,rawCarryover:m,retrievalProfile:c.retrievalProfile??"general_chat"}),recall:d}}return{async sessionStart(c){let i=await e.memory.runtime.startSession({scope:c.scope}),d=await R(c.scope,{phase:"sessionStart",status:"succeeded",traceId:i.traceId});return{state:i.state,traceId:i.traceId,events:[d]}},async beforeModelCall(c){let i=c.contextMode??s;if(c.ignoreMemory){let a=await R(c.scope,{phase:"beforeModelCall",status:"skipped",reason:"ignore_memory",contextMode:i});return{context:q(i),events:[a]}}let d=D(c.query)??N(c.messages??[]);if(!d){let a=await R(c.scope,{phase:"beforeModelCall",status:"skipped",reason:"no_query",contextMode:i});return{context:q(i),events:[a]}}if(i==="progressive"&&o){let a=await o.searchRecallIndex({scope:c.scope,query:d,includeRuntime:c.includeRuntime,retrievalProfile:c.retrievalProfile}),n=o.renderProgressiveContext({index:a,query:d,retrievalProfile:c.retrievalProfile,maxRecords:c.maxProgressiveRecords??he,maxTokens:c.maxMemoryTokens??t}),g=await R(c.scope,{phase:"beforeModelCall",status:n.content.trim()?"applied":"skipped",reason:n.content.trim()?void 0:"empty_context",contextMode:"progressive"});return{context:{mode:"progressive",content:n.content,estimatedTokens:n.estimatedTokens,omittedSections:n.omittedRecordCount>0?[`records:${n.omittedRecordCount}`]:[],recordRefs:a.records.map((l)=>l.recordRef)},events:[g]}}let f=await k(c,d),m=await R(c.scope,{phase:"beforeModelCall",status:f.context.content.trim()?"applied":"skipped",reason:f.context.content.trim()?void 0:"empty_context",contextMode:"fragment",fallbackReason:i==="progressive"?"progressive_unavailable":void 0});return{context:f.context,recall:f.recall,events:[m]}},async afterModelCall(c){let i=c.writeback??{mode:"observe"},d=i.mode??"observe",f=D(c.assistantText),m=N(c.messages),a=De({assistantText:f,userText:m}),n=[],g=[],l;if(d==="observe"&&a)n.push(O({preview:a,reason:"observe"})),g.push(_(a));else if(d==="selective"&&!V(i)&&a)n.push(O({preview:a,reason:"selective_not_allowed"})),g.push(_(a));else if(V(i)&&f&&m)l=await e.memory.remember(we({scope:c.scope,locale:c.locale,userText:m,assistantText:f}));let u=await R(c.scope,{phase:"afterModelCall",status:l||n.length>0?"applied":"skipped",reason:d==="off"?"writeback_off":l||n.length>0?void 0:"no_candidate"});return{boundedJobs:g,candidates:n,events:[u],...l?{rememberResult:l}:{},trace:{candidateCount:n.length,rawTranscriptPersisted:!1,rememberCalled:Boolean(l)}}},async sessionEnd(c){let i=await e.memory.runtime.endSession({scope:c.scope,archive:c.archive??"off"}),d=await R(c.scope,{phase:"sessionEnd",status:"succeeded",traceId:i.traceId});return{state:i.state,traceId:i.traceId,events:[d]}},async preAction(c){let d=await(e.hostAdapter??Te({hostKind:c.intent.hostKind,memory:e.memory})).assessAction(c.intent),f=W({assessment:d,intent:c.intent}),m=await R(c.intent.scope,{phase:"preAction",status:"applied",reason:d.decision});return{assessment:d,executionPlan:f,events:[m]}},async observeToolResult(c){let i=Q(`${c.toolName}: ${c.summary}`),d=await e.memory.runtime.updateSessionJournal({scope:c.scope,patch:{appendWorklog:[i]}}),f=await R(c.scope,{phase:"observeToolResult",status:"applied"});return{journal:d.journal,events:[f]}}}}
export{Ue as sa};
function i(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document query page limit must be a positive integer.")}function c(e,o){if(!o)return!0;let t=e;return Object.entries(o).every(([r,n])=>t[r]===n)}function s(e,o){return{...e,...o}}
export{i as Bb,c as Cb,s as Db};
import{Ab as l,Oa as gr,Va as br,Za as yr,ab as wr,fb as Er,mb as Kr,qb as z,ub as Or,yb as Z}from"./chunk-65h9nkw1.js";class C extends Error{diagnostics;constructor(r,o){super(r);this.diagnostics=o;this.name="HostAdapterWriteError"}}function U(r){return typeof r==="object"&&r!==null}function Wr(r){if(!U(r))return!1;let o=Object.getPrototypeOf(r);return o===null||o===Object.prototype}function R(r,o){if(typeof r!=="string"||r.trim().length===0)throw Error(`${o} must be a non-empty string`);return r.trim()}function J(r,o){if(r===void 0)return;return R(r,o)}function j(r,o){if(r===null||typeof r==="boolean"||typeof r==="number"||typeof r==="string"){if(typeof r==="number"&&!Number.isFinite(r))throw Error(`${o} must be a JSON-serializable value`);return r}if(Array.isArray(r))return r.map((s,e)=>j(s,`${o}[${e}]`));if(Wr(r)){let s={};for(let[e,H]of Object.entries(r)){if(H===void 0)throw Error(`${o}.${e} must not be undefined`);s[e]=j(H,`${o}.${e}`)}return s}throw Error(`${o} must be a JSON-serializable value`)}function cr(r,o){if(typeof r!=="number"||!Number.isInteger(r)||r<0)throw Error(`${o} must be a non-negative integer`);return r}function Cr(r,o){let s=R(r,o);if(Number.isNaN(Date.parse(s)))throw Error(`${o} must be a valid date-time string`);return s}function Gr(r,o){if(r==="generic"||r==="claude"||r==="codex")return r;throw Error(`${o} must be generic, claude, or codex`)}function Jr(r,o){if(!U(r))throw Error(`${o} must be an object`);return{userId:R(r.userId,`${o}.userId`),...r.tenantId!==void 0?{tenantId:R(r.tenantId,`${o}.tenantId`)}:{},...r.workspaceId!==void 0?{workspaceId:R(r.workspaceId,`${o}.workspaceId`)}:{},...r.agentId!==void 0?{agentId:R(r.agentId,`${o}.agentId`)}:{},...r.sessionId!==void 0?{sessionId:R(r.sessionId,`${o}.sessionId`)}:{}}}function Ur(r,o){let s=R(r,o),e=s.split("/");if(s.startsWith("/")||s.startsWith("~/")||s.includes("\\")||/^[A-Za-z]:[\\/]/.test(s))throw Error(`${o} must be a normalized relative path without traversal or absolute segments`);if(e.some((H)=>H.length===0||H==="."||H===".."))throw Error(`${o} must be a normalized relative path without traversal or absolute segments`);return s}function Yr(r,o){return{kind:"command",command:R(r.command,`${o}.command`),...r.summary!==void 0?{summary:J(r.summary,`${o}.summary`)}:{}}}function Zr(r,o){let s=r.payload===void 0?void 0:j(r.payload,`${o}.payload`);return{kind:"tool_call",toolName:R(r.toolName,`${o}.toolName`),...s!==void 0?{payload:s}:{},...r.raw!==void 0?{raw:J(r.raw,`${o}.raw`)}:{},...r.summary!==void 0?{summary:J(r.summary,`${o}.summary`)}:{}}}function Qr(r,o){if(r.operation!=="create"&&r.operation!=="delete"&&r.operation!=="update")throw Error(`${o}.operation must be create, delete, or update`);return{kind:"file_edit",operation:r.operation,relativePath:Ur(r.relativePath,`${o}.relativePath`),...r.summary!==void 0?{summary:J(r.summary,`${o}.summary`)}:{}}}function Xr(r,o){if(!U(r))throw Error(`${o} must be an object`);if(r.kind==="command")return Yr(r,o);if(r.kind==="tool_call")return Zr(r,o);if(r.kind==="file_edit")return Qr(r,o);throw Error(`${o}.kind must be command, tool_call, or file_edit`)}function v(r,o="actionIntent"){if(!U(r))throw Error(`${o} must be an object`);let s=r.runId===void 0?void 0:R(r.runId,`${o}.runId`),e=r.attemptId===void 0?void 0:R(r.attemptId,`${o}.attemptId`);if(!s&&!e)throw Error(`${o} must include runId or attemptId`);let H={actionId:R(r.actionId,`${o}.actionId`),hostKind:Gr(r.hostKind,`${o}.hostKind`),occurredAt:Cr(r.occurredAt,`${o}.occurredAt`),scope:Jr(r.scope,`${o}.scope`),sequence:cr(r.sequence,`${o}.sequence`),turnId:R(r.turnId,`${o}.turnId`),action:Xr(r.action,`${o}.action`)};if(s)return{...H,runId:s,...e?{attemptId:e}:{}};return{...H,attemptId:e}}function Lo(r){try{return v(r),!0}catch{return!1}}function u(r){return typeof r==="object"&&r!==null}function Y(r,o){if(typeof r!=="string"||r.trim().length===0)throw Error(`${o} must be a non-empty string`);return r}function x(r,o){if(typeof r!=="number"||!Number.isInteger(r)||r<0)throw Error(`${o} must be a non-negative integer`);return r}function Fr(r,o){if(r==="command"||r==="tool_call"||r==="warning")return r;throw Error(`${o} must be command, tool_call, or warning`)}function jr(r,o){if(r==="failure"||r==="success"||r==="timeout"||r==="user_corrected")return r;throw Error(`${o} must be failure, success, timeout, or user_corrected`)}function vr(r,o){if(r==="host_lifecycle"||r==="warning_message")return r;throw Error(`${o} must be host_lifecycle or warning_message`)}function q(r,o="trace.events[0]"){if(!u(r))throw Error(`${o} must be an object`);let s=r.args;if(s!==void 0&&(!Array.isArray(s)||s.some((A)=>typeof A!=="string")))throw Error(`${o}.args must be a string array`);let e=r.raw;if(e!==void 0&&typeof e!=="string")throw Error(`${o}.raw must be a string`);let H=r.evidenceExcerpt;if(H!==void 0&&typeof H!=="string")throw Error(`${o}.evidenceExcerpt must be a string`);let f=r.correctionOfStepIndex===void 0?void 0:x(r.correctionOfStepIndex,`${o}.correctionOfStepIndex`),w=x(r.stepIndex,`${o}.stepIndex`),m=r.outcomeSource===void 0?void 0:vr(r.outcomeSource,`${o}.outcomeSource`),E=r.turnId;if(E!==void 0&&typeof E!=="string")throw Error(`${o}.turnId must be a string`);return{actionKind:Fr(r.actionKind,`${o}.actionKind`),actionName:Y(r.actionName,`${o}.actionName`),...s?{args:[...s]}:{},...typeof f==="number"?{correctionOfStepIndex:f}:{},...typeof H==="string"?{evidenceExcerpt:H}:{},outcome:jr(r.outcome,`${o}.outcome`),...typeof m==="string"?{outcomeSource:m}:{},...typeof e==="string"&&e.trim().length>0?{raw:e}:{},stepIndex:w,...typeof E==="string"&&E.trim().length>0?{turnId:E}:{}}}function i(r,o="trace"){if(!u(r))throw Error(`${o} must be an object`);let s=Y(r.hostKind,`${o}.hostKind`);if(s!=="codex")throw Error(`${o}.hostKind must be codex`);let e=r.events;if(!Array.isArray(e)||e.length===0)throw Error(`${o}.events must be a non-empty array`);let H=e.map((w,m)=>q(w,`${o}.events[${m}]`)),f=new Map;for(let[w,m]of H.entries()){let E=f.get(m.stepIndex);if(E!==void 0)throw Error(`${o}.events[${w}].stepIndex duplicates ${o}.events[${E}].stepIndex`);f.set(m.stepIndex,w)}return{cue:Y(r.cue,`${o}.cue`),hostKind:s,traceId:Y(r.traceId,`${o}.traceId`),events:H}}function p(r){let o;for(let s of r.events)if(!o||s.stepIndex<o.stepIndex)o=s;return o}function T(r){return{kind:r.actionKind,name:r.actionName,...r.args?{args:[...r.args]}:{},...r.raw?{raw:r.raw}:{}}}function rr(r){if(r.events.length===0)return null;return i({cue:r.cue,hostKind:r.hostKind,traceId:r.traceId,events:r.events},"trace")}function or(r,o){return r instanceof Error?r:Error(o)}function sr(r){let o=[],s=null,e=0;return{appendEvent(H){if(s)throw Error("behavioral trace recorder is already closed");let f=q({...H,stepIndex:e},"trace.events[0]");return o.push(f),e+=1,f},close(){if(s)return s;return s=(async()=>{let H=null;try{H=rr({...r,events:o})}catch(f){return{error:or(f,"failed to build behavioral trace"),recorded:!1,trace:null}}if(!H)return{recorded:!1,trace:null};try{return{recorded:(await r.onClose?.(H))?.recorded??!1,trace:H}}catch(f){return{error:or(f,"failed to record behavioral trace"),recorded:!1,trace:H}}})(),s},snapshot(){return rr({...r,events:o})}}}var qr=Symbol.for("goodmemory.host.eval.support");function er(r,o){return r[qr]=o,r}var a="host_pre_action_policy",Tr=new Set(["a","an","and","before","by","for","from","in","into","is","of","on","or","the","then","to","with"]),kr=["avoid","blocked","do not","don't","must not","never","risk"],Hr=["before","first","precondition","prerequisite","review","run smoke","smoke verification","verify"],Lr=["deepanalyzer","deploy","drop","git push","migration","prod","production","publish","release","rm -"],Dr=["agents.md","claude.md","package.json","playbooks/","src/","task-board/"],zr={correction_context:4,verification_result:3,tool_result_excerpt:2,document_excerpt:2,conversation_excerpt:1};function N(r){let o=new Set,s=[];for(let e of r){if(!e)continue;let H=e.trim();if(H.length===0||o.has(H))continue;o.add(H),s.push(H)}return s}function b(r){return r?.trim().toLowerCase()??""}function fr(r){return r.toLowerCase().split(/[^a-z0-9_.-]+/u).map((o)=>o.trim()).filter((o)=>o.length>=3&&!Tr.has(o))}function k(r,o){if(r.length===0||o.length===0)return 0;let s=new Set(fr(o)),e=0;for(let H of fr(r))if(s.has(H))e+=1;return e}function Ar(r){switch(r.kind){case"command":return[r.command,r.summary].filter(Boolean).join(" ");case"tool_call":return[r.toolName,r.raw,r.summary,r.payload?JSON.stringify(r.payload):void 0].filter(Boolean).join(" ");case"file_edit":return[r.operation,r.relativePath,r.summary].filter(Boolean).join(" ")}}function G(r){switch(r.kind){case"command":return`command ${r.command}`;case"tool_call":return`tool ${r.toolName}`;case"file_edit":return`${r.operation} ${r.relativePath}`}}function lr(r){return r.kind==="validated_pattern"&&r.lifecycle==="active"&&!r.supersededBy}function Mr(r){let o=gr(r.appliesTo);return o==="coding_agent"||o==="general_response"}function xr(r,o){let s=r.durable.evidence.filter((f)=>f.linkedMemoryIds.includes(o)).map((f)=>f.id),e=r.durable.experiences.filter((f)=>f.linkedMemoryIds.includes(o)).flatMap((f)=>f.linkedEvidenceIds),H=r.durable.promotions.filter((f)=>f.linkedMemoryIds.includes(o)).flatMap((f)=>f.linkedEvidenceIds);return N([...ur(r,o),...s,...e,...H])}function ur(r,o){let s=r.durable.feedback.find((e)=>e.id===o);return N(s?.evidence??[])}function ir(r,o,s){let e=b(s);return r.durable.feedback.filter((H)=>lr(H)&&Mr(H)).map((H)=>{let f=[H.rule,H.why].filter(Boolean).join(" "),w=k(f,s),m=G(o.action).toLowerCase();if(!(w>0||b(f).includes(m)||b(f).includes(e)))return null;return{pattern:H,linkedEvidenceIds:xr(r,H.id),score:w+(H.why?1:0)+Math.round(H.confidence)}}).filter((H)=>Boolean(H)).sort((H,f)=>f.score-H.score)}function pr(r,o){return r.durable.evidence.map((s)=>{let e=k(s.excerpt,o);if(e===0)return null;return{evidence:s,score:e+zr[s.kind]}}).filter((s)=>Boolean(s)).sort((s,e)=>e.score-s.score)}function dr(r){if(r.kind==="file_edit"){if(r.operation==="delete")return!0;let s=b(r.relativePath);return Dr.some((e)=>s.includes(e))}let o=b(Ar(r));return Lr.some((s)=>o.includes(s))}function ro(r){let o=b(r);return kr.some((s)=>o.includes(s))}function oo(r){let o=[];for(let s of r){let e=b(s);if(!Hr.some((f)=>e.includes(f)))continue;if(e.includes("smoke")){o.push("run smoke verification");continue}if(e.includes("quickcheck")){o.push("run QuickCheck first");continue}if(e.includes("playbook")||e.includes("runbook")){o.push("read the current playbook or runbook");continue}if(e.includes("verify")){o.push("run verification first");continue}let H=s.split(/[.!?]/u).map((f)=>f.trim()).find((f)=>Hr.some((w)=>b(f).includes(w)));if(H)o.push(H)}return N(o)}function so(r){let s=(r.kind==="command"?r.command:r.kind==="tool_call"?r.raw:void 0)?.trim();if(!s)return;let[e]=s.split(/\s+/u);return e?.trim()||void 0}function eo(r,o){let s=r?.trim();if(!s||!s.includes("/"))return;let e=s.lastIndexOf("/");if(e<0)return;return`${s.slice(0,e+1)}${o}`}function Ho(r,o){let s=r[0];if(!s)return;if(b(s).includes("quickcheck")){let H=eo(so(o),"QuickCheck");if(H)return{kind:"tool_call",toolName:"QuickCheck",raw:H,summary:"Run QuickCheck before the original action."};return{kind:"warning",message:s}}return{kind:"warning",message:s}}function mr(r){return[...r.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/gu)].map((o)=>o[1]??o[2]??o[3]??"").filter((o)=>o.length>0)}function $r(r){if(r.kind==="tool_call"){let o=r.raw?.trim();return{...o?{args:mr(o).slice(1),raw:o}:{},kind:"tool_call",name:r.toolName}}if(r.kind==="command"){let o=r.command.trim(),s=mr(o);return{args:s.slice(1),kind:"command",name:s[0]??o,raw:o}}return{kind:"warning",name:"file_edit",raw:`${r.operation} ${r.relativePath}`}}function fo(r){if(r.kind==="warning")return{kind:"warning",message:r.raw??r.name};if(r.kind==="tool_call")return{kind:"tool_call",toolName:r.name,...r.raw?{raw:r.raw}:{},summary:"Use the canonical first action from validated behavioral policy."};return{command:r.raw??[r.name,...r.args??[]].filter(Boolean).join(" "),kind:"command",summary:"Use the canonical first action from validated behavioral policy."}}function mo(r,o,s){let e=Er({appliesTo:"coding_agent",feedback:r.durable.feedback,query:s,surface:"host_action"}),H=$r(o.action);return e.filter((f)=>{let w=[f.feedback.rule,f.feedback.why].filter(Boolean).join(" "),m=k(w,s),E=f.policy.applicability.canonicalFirstAction,A=E&&b(E.name)===b(H.name);return f.matchedQueryTokens.length>0||m>0||Boolean(A)}).map((f)=>({feedback:f.feedback,policy:f.policy,score:f.score})).sort((f,w)=>w.score-f.score)}function go(r){let o=[],s=dr(r.action);if(r.workingMemory?.temporaryDecisions?.length)o.push(...r.workingMemory.temporaryDecisions);if(s&&r.workingMemory?.openLoops?.length)o.push(`Open loop before proceeding: ${r.workingMemory.openLoops[0]}`);if(s&&r.journal?.workflow?.length)o.push(`Session workflow says to start with: ${r.journal.workflow[0]}`);if(r.journal?.errorsAndCorrections?.length)o.push(r.journal.errorsAndCorrections[0]);return N(o)}function wo(r){return N([a,`${a}.decision=${r.decision}`,`${a}.action_kind=${r.intent.action.kind}`,`${a}.host_kind=${r.intent.hostKind}`,r.highRisk?`${a}.high_risk`:void 0,r.matchedMemoryIds.length>0?`${a}.matched_memory=${r.matchedMemoryIds.length}`:void 0,r.matchedEvidenceIds.length>0?`${a}.matched_evidence=${r.matchedEvidenceIds.length}`:void 0])}function Eo(r){if(r.kind==="file_edit")return r.operation==="delete";if(r.kind==="command"){let o=b(r.command);return o.includes("rm -")||o.includes("git reset --hard")}return!1}function Br(r){let o=Ar(r.intent.action),s=mo(r.exported,r.intent,o),e=ir(r.exported,r.intent,o),H=pr(r.exported,o),f=N([...s.map((g)=>g.feedback.id),...e.map((g)=>g.pattern.id)]),w=N([...s.flatMap((g)=>g.feedback.evidence??[]),...e.flatMap((g)=>g.linkedEvidenceIds),...H.map((g)=>g.evidence.id)]),m=e.flatMap((g)=>[g.pattern.rule,g.pattern.why].filter((F)=>Boolean(F))),E=H.map((g)=>g.evidence.excerpt),A=oo([...m,...E]),y=go({action:r.intent.action,journal:r.exported.runtime?.journal,workingMemory:r.exported.runtime?.workingMemory}),_=N([...m,...y]).slice(0,4),$=dr(r.intent.action),B=f.length>0||w.length>0,S=[...m,...E].some((g)=>ro(g)),d="allow",t="No matched memory-backed pre-action policy applied to this action.",K,X=$r(r.intent.action),h=s[0],V=h?.policy.applicability.canonicalFirstAction;if(h&&V){if(_.unshift(h.feedback.rule),!wr(X,V))d="review_required",t="Matched typed behavioral policy requires a canonical first action before the proposed host action.",K=fo(V);else if(_.length>0)d="allow_with_guidance",t="Matched typed behavioral policy confirms the canonical first action."}if(d==="allow"&&B&&$&&(S||A.length>0))if(K=Ho(A,r.intent.action),Eo(r.intent.action)&&!K)d="blocked",t="Matched memory-backed veto blocks this destructive action before execution.";else d="review_required",t=A.length>0?`Matched memory-backed policy requires preconditions before ${G(r.intent.action)}.`:`Matched memory-backed policy requires rewriting the first step before ${G(r.intent.action)}.`,K??={kind:"warning",message:"Review matched memory guidance before continuing."};else if(d==="allow"&&_.length>0)d="allow_with_guidance",t="Matched memory or runtime continuity guidance is available for this action.";let W=wo({decision:d,highRisk:$,intent:r.intent,matchedEvidenceIds:w,matchedMemoryIds:f});return{actionId:r.intent.actionId,auditRecorded:!1,decision:d,guidance:_,matchedEvidenceIds:w,matchedMemoryIds:f,policyApplied:W,reason:t,...K?{recommendedFirstStep:K}:{},requiredPreconditions:A}}function Ao(r){if(r==="timeout")return"timeout";if(r==="user_corrected")return"user correction";return"failure"}function $o(r){return r==="failure"||r==="timeout"||r==="user_corrected"}function tr(r){return r.outcome==="success"||r.actionKind==="warning"}function Bo(r){let o=[...r.trace.events].filter((f)=>f.stepIndex>r.firstAction.stepIndex).sort((f,w)=>f.stepIndex-w.stepIndex),s=o.find((f)=>f.correctionOfStepIndex===r.firstAction.stepIndex&&tr(f)),e=o.find((f)=>tr(f)),H=s??e;return H?T(H):void 0}function to(r){let o=p(r);if(!o||!$o(o.outcome))return null;return{cue:r.cue,evidenceExcerpt:o.evidenceExcerpt,failureClass:Ao(o.outcome),firstAction:T(o),retrievalProfile:"coding_agent",saferAlternative:Bo({firstAction:o,trace:r})}}async function L(r){let o=Z(r.memory),s=to(r.trace);if(!o?.recordBehavioralOutcome||!s)return{...s?{outcome:s}:{},recorded:!1};return await o.recordBehavioralOutcome({scope:r.scope,cue:s.cue,evidenceExcerpt:s.evidenceExcerpt,failureClass:s.failureClass,firstAction:s.firstAction,saferAlternative:s.saferAlternative,modelInfluence:s.modelInfluence,outcome:s.outcome}),{outcome:s,recorded:!0}}var hr=["memory_index","user_memory","session_memory"],Nr=[...hr,"archive_recap","playbook"];function n(r){return r.trim().replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\t/g,"\\t").replace(/\r\n?/g,`
`).replace(/\n/g,"\\n")}function O(r,o){return[`## ${n(r)}`,...o.length>0?o:["- none"]].join(`
`)}function no(r,o){return[`# ${n(r)}`,...o.flatMap((s)=>["",s])].join(`
`)}function D(r,o){let s=r??o,e=[];for(let H of s)if(!e.includes(H))e.push(H);return e}function nr(r){return Object.freeze([...r])}function Io(r){if(r.kind==="archive"||r.relativePath.startsWith("archive/"))return"archive_recap";if(r.relativePath.startsWith("playbooks/"))return"playbook";if(r.relativePath==="MEMORY.md"||r.kind==="memory")return"memory_index";if(r.relativePath==="user.md"||r.kind==="user")return"user_memory";if(r.kind==="session"||r.relativePath==="session.md")return"session_memory";return null}function _o(r){let o=r.readableArtifactTypes.filter((s)=>!r.supportedReadableArtifactTypes.includes(s));if(o.length===0)return;throw Error(`readable artifact types must be supported by the configured export surface: ${o.join(", ")}`)}function Ro(r){if(r.mode!=="file-authoritative"&&r.writableArtifactTypes.length>0)throw Error("file-assisted adapters cannot declare writable artifact types");if(r.writableArtifactTypes.length>0&&!r.documentStorePresent)throw Error("file-authoritative adapters require documentStore when writable artifact types are enabled");for(let o of r.writableArtifactTypes)if(!r.readableArtifactTypes.includes(o))throw Error("writable artifact types must be a subset of readable artifact types")}function So(r){return Boolean(Z(r)?.recordBehavioralOutcome)}function bo(r){return Boolean(l(r)?.recordHostActionAssessment)}function yo(r){if(!r)return;switch(r.kind){case"warning":return r.message;case"command":return r.command;case"tool_call":return r.toolName;case"file_edit":return`${r.operation} ${r.relativePath}`}}function Ko(r,o){if(r.hostKind!==o)throw Error(`host action intent hostKind ${r.hostKind} does not match adapter hostKind ${o}`);return{...r,hostKind:o}}async function Oo(r){if(!bo(r.memory))return{auditRecorded:!1};let o=await l(r.memory).recordHostActionAssessment({assessment:{actionId:r.intent.actionId,actionKind:r.intent.action.kind,actionSummary:G(r.intent.action),attemptId:r.intent.attemptId,decision:r.assessment.decision,guidance:r.assessment.guidance,hostKind:r.intent.hostKind,matchedEvidenceIds:r.assessment.matchedEvidenceIds,matchedMemoryIds:r.assessment.matchedMemoryIds,occurredAt:r.intent.occurredAt,policyApplied:r.assessment.policyApplied,reason:r.assessment.reason,recommendedFirstStepSummary:yo(r.assessment.recommendedFirstStep),requiredPreconditions:r.assessment.requiredPreconditions,runId:r.intent.runId,scope:r.intent.scope,turnId:r.intent.turnId}});return{assessmentExperienceId:o.experienceId,auditRecorded:o.recorded}}function ho(r,o){return[`- userId: ${n(r.scope.userId)}`,r.scope.workspaceId?`- workspaceId: ${n(r.scope.workspaceId)}`:void 0,r.scope.agentId?`- agentId: ${n(r.scope.agentId)}`:void 0,`- sessionId: ${n(o)}`].filter((s)=>Boolean(s))}function No(r){if(!r)return{constraints:[],currentGoal:[],openLoops:[],recentDecisions:[]};return{currentGoal:r.currentGoal?[`- ${n(r.currentGoal)}`]:[],openLoops:r.openLoops.map((o)=>`- ${n(o)}`),recentDecisions:(r.temporaryDecisions??[]).map((o)=>`- ${n(o)}`),constraints:(r.constraints??[]).map((o)=>`- ${n(o)}`)}}function ao(r){if(!r)return{currentState:[],keyFiles:[],workflow:[]};return{currentState:r.currentState?[`- ${n(r.currentState)}`]:[],keyFiles:(r.filesAndFunctions??[]).map((o)=>`- ${n(o)}`),workflow:(r.workflow??[]).map((o)=>`- ${n(o)}`)}}function Po(r){return r.map((o)=>{let s=n(o.title),e=n(o.pointer);return`- ${s}: ${e}`})}function Vo(r){return r.map((o)=>`- [${o.kind}] ${n(o.rule)}`)}function Wo(r){return r.map((o)=>`- ${n(o.preview)}`)}function co(r){let o=new Set,s=[];for(let e of r){if(o.has(e))continue;o.add(e),s.push(e)}return s}function Ir(r){return(r.lifecycle??"active")==="active"}function Co(r){return`session-memory/${encodeURIComponent(r)}.md`}function Go(r,o){let s=r.runtime?.workingMemory?.sessionId===o?r.runtime.workingMemory:null,e=r.runtime?.journal?.sessionId===o?r.runtime.journal:null,H=r.durable.references.filter((A)=>A.sessionId===o&&Ir(A)),f=r.durable.feedback.filter((A)=>A.sessionId===o&&Ir(A)),w=(r.runtime?.spills??[]).filter((A)=>A.scope.sessionId===o),m=No(s),E=ao(e);return no(`Session Handoff: ${o}`,[O("Scope",ho(r,o)),O("Current Goal",m.currentGoal),O("Open Loops",m.openLoops),O("Recent Decisions",m.recentDecisions),O("Constraints",m.constraints),O("Current State",E.currentState),O("Key Files",co([...E.keyFiles,...Po(H)])),O("Workflow",E.workflow),O("Procedural Memory",Vo(f)),O("Artifact Spills",Wo(w))])}function Jo(r,o,s){if(s==="session_memory"&&o.sessionId)return{...o,artifactType:s,relativePath:Co(o.sessionId),content:Go(r,o.sessionId),writable:!1};return{...o,artifactType:s,writable:!1}}async function ar(r,o,s){let e=await r.exportMemory(s);return{artifacts:e.artifacts.files.flatMap((f)=>{let w=Io(f);if(!w||!o.includes(w))return[];return[Jo(e,f,w)]}),exportedAt:e.exportedAt,rootPath:e.artifacts.rootPath,scope:e.scope}}function Uo(r=!1){return{mode:"file-assisted",hint:"Recreate the host adapter in file-assisted mode and inspect compiled artifacts before retrying writable operations.",performed:r}}function P(r){return{adapterId:r.adapterId,artifactType:r.artifactType,canonicalMemoryId:r.canonicalMemoryId,failureReasons:r.failureReasons??[],hostKind:r.hostKind,mode:r.mode,policyApplied:r.policyApplied??[],provenance:{adapterId:r.adapterId,hostKind:r.hostKind,origin:"host_adapter",wroteAt:r.wroteAt},relativePath:r.relativePath,risky:r.risky??!1,rollback:Uo(r.rollbackPerformed??!1),structuredDelta:r.structuredDelta??[],verificationOutcome:r.verificationOutcome??"not_run"}}function I(r,o){return new C(r,o)}function Q(r){return r.map((o)=>o.trim()).filter((o)=>o.startsWith("- ")).map((o)=>o.slice(2).trim())}function Pr(r){let o=Q(r),s={};for(let e of o){let H=e.indexOf(":");if(H<0)continue;let f=e.slice(0,H).trim(),w=e.slice(H+1).trim();s[f]=w}return s}function M(r){let o=new Map,s=null;for(let e of r.split(/\r?\n/)){let H=e.trimEnd();if(H.startsWith("## ")){s=H.slice(3).trim(),o.set(s,[]);continue}if(s)o.get(s)?.push(H)}return o}function _r(r,o){let s=M(r);return Q(s.get(o)??[])}function Rr(r){return r.length===1&&r[0]==="none"}function Yo(r){let o=M(r.content),s=Pr(o.get("Canonical Pattern")??[]),e=Q(o.get("Guidance")??[]),H=Q(o.get("Why")??[]);if(!s.canonicalMemoryId)throw I("Malformed playbook file.",P({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback requires canonicalMemoryId in the Canonical Pattern section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(e.length===0)throw I("Malformed playbook file.",P({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback requires one guidance bullet in the Guidance section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(e.length>1)throw I("Malformed playbook file.",P({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback only supports a single guidance bullet in the Guidance section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(H.length>1)throw I("Malformed playbook file.",P({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback only supports zero or one Why bullet in the Why section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));return{appliesTo:s.appliesTo,canonicalMemoryId:s.canonicalMemoryId,rule:e[0],why:H[0]}}function Zo(r){let o=M(r),e=Pr(o.get("Canonical Pattern")??[]).canonicalMemoryId?.trim();return e?e:null}function Qo(r){return{id:"host-write-candidate",kindHint:"feedback",explicitness:"explicit",content:r.rule,sourceMessageIndex:0,sourceRole:"assistant",metadata:{appliesTo:r.appliesTo,feedbackKind:"validated_pattern"}}}function Xo(r,o){if(r.userId!==o.userId)return!1;if(o.tenantId!==void 0&&r.tenantId!==o.tenantId)return!1;if(o.workspaceId!==void 0&&r.workspaceId!==o.workspaceId)return!1;if(o.agentId!==void 0&&r.agentId!==o.agentId)return!1;return!0}function Fo(r){let o=[];if(r.previous.appliesTo!==r.nextAppliesTo)o.push({op:"set",target:"appliesTo",value:r.nextAppliesTo});if(r.previous.rule!==r.nextRule)o.push({op:"set",target:"rule",value:r.nextRule});if(r.previous.why!==r.nextWhy)o.push({op:"set",target:"why",value:r.nextWhy});return o}function jo(r){return{artifactType:r.artifactType,canonicalMemoryId:r.canonicalMemoryId,currentContent:r.currentContent,nextContent:r.nextContent,relativePath:r.relativePath,risky:r.risky,scope:r.scope,structuredDelta:r.structuredDelta}}async function Sr(r,o){let s=await ar(r,Nr,{scope:o,includeRuntime:!0});return new Map(s.artifacts.map((e)=>[e.relativePath,e]))}async function vo(r){let o=r.now(),s=(g)=>P({adapterId:r.adapterId,artifactType:r.writeInput.artifactType,canonicalMemoryId:g.canonicalMemoryId,failureReasons:g.failureReasons,hostKind:r.hostKind,mode:r.mode,policyApplied:g.policyApplied,relativePath:g.relativePath??r.writeInput.relativePath,risky:g.risky,rollbackPerformed:g.rollbackPerformed,structuredDelta:g.structuredDelta,verificationOutcome:g.verificationOutcome,wroteAt:o});if(!r.writeInput.relativePath.startsWith("playbooks/")||r.writeInput.relativePath.endsWith(".prompt.md")||r.writeInput.relativePath.endsWith(".skill.md"))throw I(`Host adapter does not allow writes for artifact path ${r.writeInput.relativePath}`,s({failureReasons:["Structured delta writeback only supports canonical playbook markdown files."]}));let H=(await Sr(r.memory,r.writeInput.scope)).get(r.writeInput.relativePath);if(!H)throw I(`Host adapter cannot locate the current artifact ${r.writeInput.relativePath}`,s({failureReasons:["The requested artifact path does not exist in the current exported host surface."]}));let f=Zo(H.content);if(r.writeInput.content===H.content)return{diagnostics:s({canonicalMemoryId:f??void 0,policyApplied:[],risky:!1,structuredDelta:[]}),status:"noop",updatedArtifact:H};let w;try{w=Yo(r.writeInput)}catch(g){if(g instanceof C)throw I(g.message,s({...g.diagnostics,adapterId:r.adapterId,hostKind:r.hostKind,mode:r.mode,relativePath:r.writeInput.relativePath,provenance:{adapterId:r.adapterId,hostKind:r.hostKind,origin:"host_adapter",wroteAt:o}}));throw g}if(!f)throw I(`Host adapter cannot verify canonical binding for ${r.writeInput.relativePath}`,s({failureReasons:["The current exported playbook is missing canonicalMemoryId and cannot be used for authoritative writeback."]}));if(w.canonicalMemoryId!==f)throw I("Host adapter write targets a different canonical record than the current playbook path.",s({canonicalMemoryId:f,failureReasons:["Edited playbook canonicalMemoryId must match the current artifact bound to this path."]}));let m=await r.documentStore.get("feedback",f);if(!m||m.kind!=="validated_pattern"||m.lifecycle!=="active"||!Xo(m,r.writeInput.scope))throw I(`Host adapter cannot find writable validated pattern ${f}`,s({canonicalMemoryId:f,failureReasons:["Structured delta writeback only supports the active validated pattern currently bound to this playbook path."]}));let E=Qo({appliesTo:w.appliesTo,rule:w.rule}),A=[],y={locale:m.source.locale??"en-US",localeSource:"default",phase:"remember",scope:r.writeInput.scope};if(r.policy?.redact){let g=await r.policy.redact(E,y);if(g.content!==E.content||g.metadata?.appliesTo!==E.metadata.appliesTo)A.push("custom_redact");E={...E,content:g.content,metadata:{...E.metadata,...g.metadata,feedbackKind:"validated_pattern"}}}if(r.policy?.shouldRemember&&!await r.policy.shouldRemember(E,y))throw A.push("custom_shouldRemember"),I("Host adapter write was blocked by policy.",s({canonicalMemoryId:m.id,failureReasons:["Policy rejected the adapter-authored change."],policyApplied:A}));let _=m.rule!==E.content,$=_r(H.content,"Why"),B=_r(r.writeInput.content,"Why"),S=m.why===void 0&&Rr(B)&&($.length===0||Rr($))?void 0:w.why,d=Fo({nextAppliesTo:E.metadata.appliesTo,nextRule:E.content,nextWhy:S,previous:m});if(d.length===0)return{diagnostics:s({canonicalMemoryId:m.id,policyApplied:A,risky:_,structuredDelta:d}),status:"noop",updatedArtifact:H};if(r.policy?.resolveConflict){let g=await r.policy.resolveConflict(Kr(m,"feedback"),E,y);if(g.action==="keep_existing")throw A.push("custom_resolveConflict"),I("Host adapter write was blocked by conflict policy.",s({canonicalMemoryId:m.id,failureReasons:[g.reason??"Conflict policy kept the existing canonical memory."],policyApplied:A,risky:_,structuredDelta:d}))}let t="not_run",K;if(_){if(!r.verifyWrite)t="review_required",K="Risky adapter writes require verification before they can be applied.";else{let g=await r.verifyWrite(jo({artifactType:r.writeInput.artifactType,canonicalMemoryId:m.id,currentContent:H.content,nextContent:r.writeInput.content,relativePath:r.writeInput.relativePath,risky:_,scope:r.writeInput.scope,structuredDelta:d}));t=g.outcome,K=g.reason}if(t!=="passed")throw I("Host adapter write requires verification.",s({canonicalMemoryId:m.id,failureReasons:[K??"Risky adapter writes require verification before they can be applied."],policyApplied:A,risky:_,structuredDelta:d,verificationOutcome:t}))}let X=br({...m,appliesTo:E.metadata.appliesTo,rule:E.content,source:yr(m.source),updatedAt:o,why:S}),h=r.createId(),V=Or({id:h,userId:m.userId,tenantId:m.tenantId,workspaceId:m.workspaceId,agentId:m.agentId,sessionId:r.writeInput.scope.sessionId,kind:"feedback",traceId:`host-write-${h}`,trigger:"governance",modelInfluence:"none",summary:`Host adapter ${r.adapterId} updated validated pattern ${m.id}.`,policyApplied:A,linkedMemoryIds:[m.id],metrics:{},createdAt:o}),W=!1;try{await r.documentStore.set("feedback",m.id,X),await r.documentStore.set(z,h,V);let F=[...(await Sr(r.memory,r.writeInput.scope)).values()].find((c)=>c.artifactType==="playbook"&&c.relativePath.endsWith(".md")&&!c.relativePath.endsWith(".prompt.md")&&!c.relativePath.endsWith(".skill.md")&&c.content.includes(`canonicalMemoryId: ${m.id}`))??H;return{diagnostics:s({canonicalMemoryId:m.id,policyApplied:A,risky:_,structuredDelta:d,verificationOutcome:t}),linkedExperienceId:h,status:"applied",updatedArtifact:F}}catch(g){W=!0;try{await r.documentStore.set("feedback",m.id,m),await r.documentStore.delete(z,h)}catch{W=!1}throw I("Host adapter write failed.",s({canonicalMemoryId:m.id,failureReasons:[g instanceof Error?g.message:String(g)],policyApplied:A,risky:_,rollbackPerformed:W,structuredDelta:d,verificationOutcome:t}))}}function qo(r,o,s){if(!r.includes(o.artifactType))throw I(`Host adapter does not allow writes for artifact type ${o.artifactType}`,s);throw I(`Structured delta writeback is not implemented yet for artifact type ${o.artifactType}`,s)}function Is(r){let o=D(r.readableArtifactTypes,hr),s=D(r.supportedReadableArtifactTypes,Nr),e=D(r.writableArtifactTypes,[]),H=r.mode??"file-assisted",f=r.now??(()=>new Date().toISOString()),w=r.createId??(()=>crypto.randomUUID());if(r.id.trim().length===0)throw Error("host adapter id must not be empty");_o({readableArtifactTypes:o,supportedReadableArtifactTypes:s}),Ro({documentStorePresent:Boolean(r.documentStore),mode:H,readableArtifactTypes:o,writableArtifactTypes:e});let m=nr(o),E=nr(e),A=Object.freeze({mode:H,readableArtifactTypes:m,writableArtifactTypes:E}),y=r.hostKind??"generic",_={id:r.id,hostKind:y,capabilities:A,async assessAction($){let B=Ko(v($),y),S=await r.memory.exportMemory({scope:B.scope,includeRuntime:Boolean(B.scope.sessionId)}),d=Br({exported:S,intent:B}),t=await Oo({assessment:d,intent:B,memory:r.memory});return{...d,...t}},async readArtifacts($){let B=await ar(r.memory,m,$);return{...B,artifacts:B.artifacts.map((S)=>({...S,writable:E.includes(S.artifactType)}))}},async writeArtifact($){let B=P({adapterId:r.id,artifactType:$.artifactType,hostKind:y,mode:H,relativePath:$.relativePath,wroteAt:f()});if($.artifactType==="playbook"&&E.includes("playbook"))return vo({adapterId:r.id,createId:w,documentStore:r.documentStore,hostKind:y,memory:r.memory,mode:H,now:f,policy:r.policy,verifyWrite:r.verifyWrite,writeInput:$});return qo(E,$,B)}};if(y==="codex"){let $=So(r.memory)?r.memory:void 0;er(_,{createBehavioralTraceRecorder:({cue:B,scope:S,traceId:d})=>sr({cue:B,hostKind:"codex",traceId:d??`host-trace-${w()}`,onClose:async(t)=>{if(!$)return{recorded:!1};return{recorded:(await L({memory:$,scope:S,trace:t})).recorded}}}),...$?{recordBehavioralTrace:async({scope:B,trace:S})=>{return{recorded:(await L({memory:$,scope:B,trace:S})).recorded}}}:{}})}return Object.freeze(_)}function Vr(r){switch(r.kind){case"command":return{kind:"command",command:r.command,...r.summary?{summary:r.summary}:{}};case"tool_call":return{kind:"tool_call",toolName:r.toolName,...r.payload!==void 0?{payload:r.payload}:{},...r.raw?{raw:r.raw}:{},...r.summary?{summary:r.summary}:{}};case"file_edit":return{kind:"file_edit",operation:r.operation,relativePath:r.relativePath,...r.summary?{summary:r.summary}:{}}}}function To(r){if(r.kind==="warning")return{kind:"warning",message:r.message};return Vr(r)}function Ss(r){if(r.assessment.actionId!==r.intent.actionId)throw Error("host action assessment actionId must match the planned intent actionId");let o=Vr(r.intent.action);switch(r.assessment.decision){case"allow":case"allow_with_guidance":return{actionId:r.intent.actionId,blocked:!1,decision:r.assessment.decision,effectiveFirstStep:o,executeOriginalActionNow:!0,guidance:[...r.assessment.guidance],intercepted:!1,originalAction:o,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!1};case"review_required":{if(!r.assessment.recommendedFirstStep)throw Error("review_required host action assessments must provide a recommendedFirstStep");return{actionId:r.intent.actionId,blocked:!1,decision:r.assessment.decision,effectiveFirstStep:To(r.assessment.recommendedFirstStep),executeOriginalActionNow:!1,guidance:[...r.assessment.guidance],intercepted:!0,originalAction:o,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!0}}case"blocked":return{actionId:r.intent.actionId,blocked:!0,decision:r.assessment.decision,executeOriginalActionNow:!1,guidance:[...r.assessment.guidance],intercepted:!0,originalAction:o,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!1}}}
export{C as Ga,v as Ha,Lo as Ia,Is as Ja,Ss as Ka};
import{Jb as D}from"./chunk-84dyzpkj.js";import{Lb as q,Nb as K}from"./chunk-m205c7rp.js";var S=q((kz,O)=>{var{create:m,defineProperty:v,getOwnPropertyDescriptor:_,getOwnPropertyNames:a,getPrototypeOf:n}=Object,r=Object.prototype.hasOwnProperty,t=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},I=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of a(B))if(!r.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=_(B,G))||H.enumerable})}return z},V=(z,B,F)=>(F=z!=null?m(n(z)):{},I(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),e=(z)=>I(v({},"__esModule",{value:!0}),z),M={};t(M,{findRootDir:()=>Bz,getUserDataDir:()=>Fz});O.exports=e(M);var Y=V(K("path")),o=V(K("fs")),J=V(K("os")),zz=D();function Bz(){try{let z=process.cwd();while(z!==Y.default.dirname(z)){let B=Y.default.join(z,".vercel");if(o.default.existsSync(B))return z;z=Y.default.dirname(z)}}catch(z){throw new zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Fz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(J.default.platform()){case"darwin":return Y.default.join(J.default.homedir(),"Library/Application Support");case"linux":return Y.default.join(J.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var u=q((fz,l)=>{var{create:Gz,defineProperty:b,getOwnPropertyDescriptor:Hz,getOwnPropertyNames:Kz,getPrototypeOf:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},j=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Kz(B))if(!Wz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=Hz(B,G))||H.enumerable})}return z},E=(z,B,F)=>(F=z!=null?Gz(Qz(z)):{},j(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Yz=(z)=>j(b({},"__esModule",{value:!0}),z),x={};Xz(x,{isValidAccessToken:()=>vz,readAuthConfig:()=>$z,writeAuthConfig:()=>qz});l.exports=Yz(x);var Z=E(K("fs")),y=E(K("path")),Zz=P();function C(){let z=(0,Zz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return y.join(z,"auth.json")}function $z(){try{let z=C();if(!Z.existsSync(z))return null;let B=Z.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function qz(z){let B=C(),F=y.dirname(B);if(!Z.existsSync(F))Z.mkdirSync(F,{mode:504,recursive:!0});Z.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function vz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var k=q((iz,g)=>{var{defineProperty:R,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz}=Object,Lz=Object.prototype.hasOwnProperty,Jz=(z,B)=>{for(var F in B)R(z,F,{get:B[F],enumerable:!0})},Vz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Lz.call(z,G)&&G!==F)R(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},Az=(z)=>Vz(R({},"__esModule",{value:!0}),z),c={};Jz(c,{processTokenResponse:()=>Dz,refreshTokenRequest:()=>Tz});g.exports=Az(c);var A=K("os"),Nz="https://vercel.com",Rz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",h=`@vercel/oidc node-${process.version} ${(0,A.platform)()} (${(0,A.arch)()}) ${(0,A.hostname)()}`,N=null;async function wz(){if(N)return N;let z=`${Nz}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":h}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return N=H,H}async function Tz(z){let B=await wz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":h},body:new URLSearchParams({client_id:Rz,grant_type:"refresh_token",...z})})}async function Dz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var P=q((dz,s)=>{var{create:Iz,defineProperty:U,getOwnPropertyDescriptor:Mz,getOwnPropertyNames:Oz,getPrototypeOf:Sz}=Object,jz=Object.prototype.hasOwnProperty,Ez=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},i=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Oz(B))if(!jz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=Mz(B,G))||H.enumerable})}return z},d=(z,B,F)=>(F=z!=null?Iz(Sz(z)):{},i(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),xz=(z)=>i(U({},"__esModule",{value:!0}),z),p={};Ez(p,{assertVercelOidcTokenResponse:()=>w,findProjectInfo:()=>uz,getTokenPayload:()=>hz,getVercelCliToken:()=>Cz,getVercelDataDir:()=>yz,getVercelOidcToken:()=>lz,isExpired:()=>gz,loadToken:()=>cz,saveToken:()=>Pz});s.exports=xz(p);var $=d(K("path")),Q=d(K("fs")),X=D(),L=S(),W=u(),f=k();function yz(){let B=(0,L.getUserDataDir)();if(!B)return null;return $.join(B,"com.vercel.cli")}async function Cz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,f.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,f.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function lz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return w(T),T}function w(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function uz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=$.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function Pz(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=$.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync($.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function cz(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=$.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return w(H),H}function hz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function gz(z){return z.exp*1000<Date.now()}});export default P();
export{P as Ib};
import{Bb as z$,Cb as x,Db as _$}from"./chunk-ch700phs.js";import{Fb as m,Gb as q$}from"./chunk-jd15jhte.js";import{Mb as T$}from"./chunk-m205c7rp.js";import{Database as D$}from"bun:sqlite";import{Buffer as l$}from"node:buffer";import{mkdirSync as c$}from"node:fs";import{dirname as d$}from"node:path";import{spawnSync as w$}from"node:child_process";import{existsSync as g$}from"node:fs";var d={};T$(d,{loadVss:()=>j$,loadVector:()=>J$,load:()=>S$,getVssLoadablePath:()=>H$,getVectorLoadablePath:()=>B$});import{join as R$}from"node:path";import{fileURLToPath as f$}from"node:url";import{arch as c,platform as v}from"node:process";import{statSync as y$}from"node:fs";var W$=[["darwin","x64"],["darwin","arm64"],["linux","x64"]];function L$($,G){return W$.find(([X,H])=>$==X&&G===H)!==null}function N$($){if($==="win32")return"dll";if($==="darwin")return"dylib";return"so"}function x$($,G){return`sqlite-vss-${$==="win32"?"windows":$}-${G}`}function Y$($){if(!L$(v,c))throw Error(`Unsupported platform for sqlite-vss, on a ${v}-${c} machine, but not in supported platforms (${W$.map(([H,Y])=>`${H}-${Y}`).join(",")}). Consult the sqlite-vss NPM package README for details. `);let G=x$(v,c),X=R$(f$(new URL(".",import.meta.url)),"..","..",G,"lib",`${$}.${N$(v)}`);if(!y$(X,{throwIfNoEntry:!1}))throw Error(`Loadble extension for sqlite-vss not found. Was the ${G} package installed? Avoid using the --no-optional flag, as the optional dependencies for sqlite-vss are required.`);return X}function B$(){return Y$("vector0")}function H$(){return Y$("vss0")}function J$($){$.loadExtension(B$())}function j$($){$.loadExtension(H$())}function S$($){J$($),j$($)}var i="vss_inner_product",h$=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/usr/lib/x86_64-linux-gnu/libsqlite3.so","/usr/lib/aarch64-linux-gnu/libsqlite3.so","/usr/lib64/libsqlite3.so","/usr/lib/libsqlite3.so"],v$=`
import { Database } from "bun:sqlite";
const [customLibraryPath, vectorPath, vssPath] = process.argv.slice(1);
if (!customLibraryPath || !vectorPath || !vssPath) {
throw new Error("Missing sqlite-vss probe paths.");
}
Database.setCustomSQLite(customLibraryPath);
const database = new Database(":memory:", { strict: true });
try {
database.loadExtension(vectorPath);
database.loadExtension(vssPath);
database.query("select vss_version() as version").get();
database.exec(
"CREATE VIRTUAL TABLE __goodmemory_vss_probe USING vss0(embedding(3)); DROP TABLE __goodmemory_vss_probe;",
);
} finally {
database.close();
}
`;function R($){if(!$)return;let G=$.trim();return G.length>0?G:void 0}function b$($){let G=R($);if(!G)return[];return G.split(",").map((X)=>X.trim()).filter((X)=>X.length>0)}function m$($){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION: ${$}. Expected a valid SQLite function identifier.`);return $}function p$($){let G=R($);if(!G)return;if(G==="off"||G==="prefer"||G==="require")return G;throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_MODE: ${G}. Expected off|prefer|require.`)}function s($){let{backend:G,customLibraryPath:X,entryPoint:H,mode:Y,path:A,paths:Z,searchFunction:j}=$;return{customLibraryPath:X,vectorExtension:{backend:G,entryPoint:H,mode:Y,path:A,paths:Z,searchFunction:j}}}function K$($){return{config:s({backend:"none",customLibraryPath:$.customLibraryPath,entryPoint:void 0,mode:"off",path:void 0,paths:[],searchFunction:$.searchFunction}),diagnostics:{available:$.source==="disabled",backend:"none",effectiveMode:"off",reason:$.reason,requestedMode:$.requestedMode,source:$.source}}}function u$($){let G=w$(process.execPath,["-e",v$,"--",$.customLibraryPath,...$.paths],{encoding:"utf8",timeout:1e4});if(G.error)return{loadable:!1,reason:G.error.message};if(G.status!==0)return{loadable:!1,reason:`${G.stdout}${G.stderr}`.trim()||`sqlite-vss probe exited with status ${G.status}`};return{loadable:!0}}function r$($={}){let G=$.exists??g$,X=($.libraryCandidatePaths??h$).find((H)=>G(H));if(!X)return{runtime:null};try{let H=d,Y=Object.hasOwn($,"getVectorLoadablePath")?$.getVectorLoadablePath:H.getVectorLoadablePath,A=Object.hasOwn($,"getVssLoadablePath")?$.getVssLoadablePath:H.getVssLoadablePath;if(!Y||!A)return{runtime:null};let Z=Y(),j=A();if(!G(Z)||!G(j))return{runtime:null};let F={customLibraryPath:X,paths:[Z,j]},_=($.probeRuntime??u$)(F);if(!_.loadable)return{runtime:null,unavailableReason:_.reason??"Bundled sqlite-vss runtime probe failed."};return{runtime:F}}catch(H){return{runtime:null,unavailableReason:`Failed to inspect bundled sqlite-vss runtime: ${H instanceof Error?H.message:String(H)}`}}}function O$($=process.env,G){let X=R($.GOODMEMORY_SQLITE_CUSTOM_LIBRARY_PATH),H=R($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),Y=b$($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),A=p$($.GOODMEMORY_SQLITE_VECTOR_MODE),Z=m$(R($.GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION)??i),j=R($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_ENTRYPOINT),F=G?.inspectBundledSQLiteVssRuntime?G.inspectBundledSQLiteVssRuntime():G?.detectBundledSQLiteVssRuntime?{runtime:G.detectBundledSQLiteVssRuntime()}:r$(),_=F.runtime,O=F.unavailableReason,W=A??(Y.length>0||_||O?"prefer":"off");if(W==="off")return K$({customLibraryPath:X,requestedMode:W,searchFunction:Z,source:"disabled"});if(Y.length>0)return{config:s({backend:"sql-function",customLibraryPath:X,entryPoint:j,mode:W,path:H,paths:Y,searchFunction:Z}),diagnostics:{available:!0,backend:"sql-function",effectiveMode:W,requestedMode:W,source:"env"}};if(_){let U=W==="require"?"require":"prefer";return{config:s({backend:"sqlite-vss",customLibraryPath:X??_.customLibraryPath,entryPoint:j,mode:U,path:_.paths.join(","),paths:_.paths,searchFunction:Z}),diagnostics:{available:!0,backend:"sqlite-vss",effectiveMode:U,requestedMode:W,source:"bundled-sqlite-vss"}}}return K$({customLibraryPath:X,requestedMode:W,searchFunction:Z,source:"unavailable",reason:O??"SQLite vector acceleration was requested, but no supported sqlite-vss runtime assets were detected and no manual GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH was configured."})}function U$($,G){if(!$.customLibraryPath)return;G.setCustomSQLite($.customLibraryPath)}function k$($,G){if($.mode==="off"||!($.paths?.length??0))return{loaded:!1,reason:"SQLite vector acceleration is disabled."};try{for(let X of $.paths)G.loadExtension(X,$.entryPoint);return{loaded:!0}}catch(X){let H=X instanceof Error?X.message:String(X);if($.mode==="prefer")return{loaded:!1,reason:`Failed to load SQLite vector extension at ${$.path}: ${H}`};throw Error(`Failed to load SQLite vector extension at ${$.path}: ${H}`)}}var b=null,o=null;function s$(){if(!b)b={customLibraryPath:Q$().config.customLibraryPath},U$(b,D$);return b}function Q$(){if(!o)o=O$();return o}function i$($,G){if(G?.readOnly||$===":memory:")return;c$(d$($),{recursive:!0})}function n($,G){return s$(),i$($,G),new D$($,{create:G?.readOnly?!1:!0,readonly:G?.readOnly??!1,strict:!0})}function o$($){$.exec(`
CREATE TABLE IF NOT EXISTS documents (
collection TEXT NOT NULL,
id TEXT NOT NULL,
json TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
`)}function a$($){$.exec(`
CREATE TABLE IF NOT EXISTS session_buffers (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_working_memory (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_journals (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`)}function n$($){$.exec(`
CREATE TABLE IF NOT EXISTS vectors (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding_json TEXT NOT NULL,
metadata_json TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE TABLE IF NOT EXISTS vector_index_state (
table_name TEXT PRIMARY KEY,
collection TEXT NOT NULL,
dimension INTEGER NOT NULL,
dirty INTEGER NOT NULL
);
`)}function D($){return JSON.parse($)}function L($,G){let X=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(G);return X!==null&&X!==void 0}function S($){return Error(`SQLite ${$} store is read-only in this context.`)}function t$($,G){let X=Math.min($.length,G.length),H=0;for(let Y=0;Y<X;Y+=1)H+=$[Y]*G[Y];return H}function e$($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function A$($){let{alias:G,keyParameterIndex:X,value:H,valueParameterIndex:Y}=$,A=`EXISTS (
SELECT 1
FROM json_each(metadata_json) AS ${G}
WHERE ${G}.key = ?${X}`;if(H===null)return`${A}
AND ${G}.type = 'null'
)`;if(typeof H==="boolean")return`${A}
AND ${G}.type = '${H?"true":"false"}'
)`;if(typeof H==="number")return`${A}
AND ${G}.type IN ('integer', 'real')
AND ${G}.atom = ?${Y}
)`;return`${A}
AND ${G}.type = 'text'
AND ${G}.atom = ?${Y}
)`}function N($){return`"${$.replaceAll('"','""')}"`}function $4($){if(/^[A-Za-z0-9]+$/.test($))return $;return`x_${l$.from($,"utf8").toString("hex")}`}function F$($,G){return`vss_vectors_${$4($)}_dim_${G}`}function p($,G,X){$.query(`DELETE FROM ${N(G)} WHERE rowid = ?1`).run(X)}function M$($){let{database:G,embeddingJson:X,rowid:H,tableName:Y}=$;p(G,Y,H),G.query(`INSERT INTO ${N(Y)} (rowid, embedding)
VALUES (?1, json(?2))`).run(H,X)}function G4($){let{collection:G,config:X,database:H,filter:Y,queryEmbedding:A,topK:Z}=$;if(X.mode==="off"||!X.paths?.length)return null;let j=[G,JSON.stringify(A)],F=[];if(Y)for(let[W,U]of Object.entries(Y)){if(!e$(U))return null;j.push(W);let Q=j.length,C=`metadata_filter_${F.length+1}`;if(U===null||typeof U==="boolean"){F.push(A$({alias:C,keyParameterIndex:Q,value:U}));continue}j.push(U),F.push(A$({alias:C,keyParameterIndex:Q,value:U,valueParameterIndex:j.length}))}j.push(Z);let _=["collection = ?1",...F];return H.query(`SELECT
id,
embedding_json,
metadata_json,
content,
${X.searchFunction||i}(embedding_json, ?2) AS score
FROM vectors
WHERE ${_.join(" AND ")}
ORDER BY score DESC, id ASC
LIMIT ?${j.length}`).all(...j).map((W)=>({id:W.id,embedding:D(W.embedding_json),metadata:D(W.metadata_json),content:W.content,score:Number(W.score)}))}function M4($,G){let X=n($,G);if(!G?.readOnly)o$(X);let H=X.query(`INSERT INTO documents (collection, id, json)
VALUES (?1, ?2, ?3)
ON CONFLICT(collection, id) DO UPDATE SET json = excluded.json`),Y=X.query("SELECT json FROM documents WHERE collection = ?1 AND id = ?2"),A=X.query("SELECT json FROM documents WHERE collection = ?1"),Z=X.query(`SELECT id, json
FROM documents
WHERE collection = ?1 AND (?2 IS NULL OR id > ?2)
ORDER BY id ASC
LIMIT ?3`),j=X.query("DELETE FROM documents WHERE collection = ?1 AND id = ?2");function F(O){let W=O instanceof Error?O.message:String(O);return/SQLITE_BUSY|SQLITE_LOCKED|database is locked|database is busy/i.test(W)}function _(O){try{X.exec("BEGIN IMMEDIATE")}catch(W){if(F(W))return!1;throw W}try{let W=Y.get(O.expected.collection,O.expected.id);if(!W||W.json!==JSON.stringify(O.expected.document))return X.exec("ROLLBACK"),!1;for(let U of O.set)H.run(U.collection,U.id,JSON.stringify(U.document));return X.exec("COMMIT"),!0}catch(W){try{X.exec("ROLLBACK")}catch{}if(F(W))return!1;throw W}}return{async set(O,W,U){H.run(O,W,JSON.stringify(U))},async get(O,W){let U=Y.get(O,W);return U?D(U.json):null},async update(O,W,U){let Q=await this.get(O,W);if(!Q)throw Error(`Document not found for update: ${O}/${W}`);await this.set(O,W,_$(Q,U))},async query(O,W){return A.all(O).map((Q)=>D(Q.json)).filter((Q)=>x(Q,W))},async queryPage(O,W){z$(W);let U=[],Q=Math.max(64,W.limit+1),C=W.cursor??null;while(U.length<=W.limit){let V=Z.all(O,C,Q);if(V.length===0)break;for(let u of V){let f=D(u.json);if(x(f,W.filter)){if(U.push({document:f,id:u.id}),U.length>W.limit)break}}if(C=V.at(-1).id,V.length<Q)break}let w=U.slice(0,W.limit);return{items:w.map(({document:V})=>V),...U.length>W.limit?{nextCursor:w.at(-1).id}:{}}},async writeBatchIfUnchanged(O){if(G?.readOnly)throw S("document");return _(O)},async delete(O,W){j.run(O,W)}}}function a($,G,X){if(X?.readOnly&&!L($,G))return{async set(){throw S("session")},async get(){return null},async deleteByScope(){throw S("session")}};let H=$.query(`INSERT INTO ${G} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO UPDATE SET json = excluded.json`),Y=$.query(`SELECT json FROM ${G} WHERE scope_key = ?1`),A=$.query(`DELETE FROM ${G} WHERE scope_key = ?1`),Z=$.query(`DELETE FROM ${G} WHERE scope_key LIKE ?1`);return{async set(j,F){H.run(m(j),JSON.stringify(F))},async get(j){let F=Y.get(m(j));return F?D(F.json):null},async deleteByScope(j){if(j.sessionId!==void 0){let _=A.run(m(j));return Number(_.changes??0)}let F=Z.run(`${q$(j)}%`);return Number(F.changes??0)}}}function q4($,G){let X=n($,G);if(!G?.readOnly)a$(X);let H=a(X,"session_buffers",G),Y=a(X,"session_working_memory",G),A=a(X,"session_journals",G);return{saveBuffer(Z,j){return H.set(Z,j)},getBuffer(Z){return H.get(Z)},deleteBuffersByScope(Z){return H.deleteByScope(Z)},saveWorkingMemory(Z,j){return Y.set(Z,j)},getWorkingMemory(Z){return Y.get(Z)},deleteWorkingMemoryByScope(Z){return Y.deleteByScope(Z)},saveJournal(Z,j){return A.set(Z,j)},getJournal(Z){return A.get(Z)},deleteJournalsByScope(Z){return A.deleteByScope(Z)}}}function z4($,G,X){let H=X?.runtimeResolution??Q$(),Y=X?.vectorExtensionConfig??H.config.vectorExtension,A=X?.runtimeResolution?.diagnostics??H.diagnostics,Z=n($,G);if(!G?.readOnly)n$(Z);if(A.requestedMode==="require"&&!A.available)throw Error(A.reason??"SQLite vector acceleration is required but no supported runtime is available.");let j=!G?.readOnly||L(Z,"vectors"),F=new Set,_=null,O=G?.readOnly?null:Z.query(`INSERT INTO vectors (
collection,
id,
embedding_json,
metadata_json,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(collection, id) DO UPDATE SET
embedding_json = excluded.embedding_json,
metadata_json = excluded.metadata_json,
content = excluded.content`),W=j?Z.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,U=j?Z.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,Q=j?Z.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,C=j?Z.query(`SELECT rowid, embedding_json
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,w=j?Z.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND rowid = ?2`):null,V=G?.readOnly?null:Z.query("DELETE FROM vectors WHERE collection = ?1 AND id = ?2"),f=!G?.readOnly||L(Z,"vector_index_state")?Z.query(`SELECT dirty
FROM vector_index_state
WHERE table_name = ?1`):null,P$=G?.readOnly?null:Z.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 1)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 1`),C$=G?.readOnly?null:Z.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 0)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 0`);function t(){if(_)return _;let B=(X?.loadVectorExtension??k$)(Y,Z);return _=B&&typeof B==="object"&&"loaded"in B?B:{loaded:Y.mode!=="off"&&Boolean(Y.paths?.length)},_}function r(){return Y.backend==="sqlite-vss"&&t().loaded}function l(B,k){let J=F$(B,k);P$.run(J,B,k)}function V$(B){C$.run(B.tableName,B.collection,B.dimension)}function e(B){if(!B.existed)return!0;let k=f.get(B.tableName);return!k||k.dirty!==0}function $$(B){return f?.get(B)?.dirty===0}function G$(B,k,J){let K=Q.all(B).filter((z)=>{return D(z.embedding_json).length===k}),M=new Set(K.map((z)=>z.rowid)),q=Z.query(`SELECT rowid FROM ${N(J)}`).all();for(let z of q)if(!M.has(z.rowid))p(Z,J,z.rowid);for(let z of K)M$({database:Z,embeddingJson:z.embedding_json,rowid:z.rowid,tableName:J});V$({collection:B,dimension:k,tableName:J})}function g(B,k){if(!r())return null;let J=F$(B,k);if(F.has(J)){if(G?.readOnly){if(!$$(J))return F.delete(J),null;return J}if(e({existed:!0,tableName:J}))G$(B,k,J);return J}if(G?.readOnly){if(!L(Z,J))return null;if(!$$(J))return null;return F.add(J),J}let K=L(Z,J);if(Z.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${N(J)}
USING vss0(embedding(${k}))`),e({existed:K,tableName:J}))G$(B,k,J);return F.add(J),J}function E$(B){let{collection:k,filter:J,queryEmbedding:K,topK:M}=B,q=K.length,z=g(k,q);if(!z)return null;let P=U.all(k).filter((T)=>{return D(T.embedding_json).length===q}).length;if(P===0)return[];let h=JSON.stringify(K),E=Math.min(P,Math.max(M,J?M*4:M));while(E>0){let T=Z.query(`SELECT rowid, distance
FROM ${N(z)}
WHERE vss_search(embedding, vss_search_params(json(?1), ?2))`).all(h,E),I=[];for(let X$ of T){let y=w.get(k,X$.rowid);if(!y)continue;let I$=D(y.embedding_json),Z$=D(y.metadata_json);if(!x(Z$,J))continue;I.push({id:y.id,embedding:I$,metadata:Z$,content:y.content,score:1/(1+Number(X$.distance))})}if(!J||I.length>=M||E>=P)return I.slice(0,M);E=Math.min(P,E*2)}return[]}return{async upsert(B,k){if(G?.readOnly)throw S("vector");Z.transaction((K)=>{let M=r();for(let q of K){let z=C.get(B,q.id),P=z?D(z.embedding_json).length:null,h=JSON.stringify(q.embedding);if(O.run(B,q.id,h,JSON.stringify(q.metadata),q.content),!M){if(z&&P!==null&&P!==q.embedding.length)l(B,P);l(B,q.embedding.length);continue}let E=C.get(B,q.id);if(!E)continue;if(z&&P!==null&&P!==q.embedding.length){let I=g(B,P);if(I)p(Z,I,z.rowid)}let T=g(B,q.embedding.length);if(!T)continue;M$({database:Z,embeddingJson:h,rowid:E.rowid,tableName:T})}})(k)},async get(B,k){if(!j)return null;let J=W.get(B,k);if(!J)return null;return{id:J.id,embedding:D(J.embedding_json),metadata:D(J.metadata_json),content:J.content}},async search(B,k,J){if(J.topK<=0||k.length===0)return[];if(!j)return[];if(Y.mode!=="off"&&Y.paths?.length&&t().loaded)try{let K=Y.backend==="sqlite-vss"?E$({collection:B,filter:J.filter,queryEmbedding:k,topK:J.topK}):(X?.runExtensionSearch??G4)({collection:B,config:Y,database:Z,filter:J.filter,queryEmbedding:k,topK:J.topK});if(K!==null)return K;if(Y.mode==="require")throw Error("SQLite vector extension search could not satisfy the current query without durable fallback.")}catch(K){if(Y.mode==="require"){let M=K instanceof Error?K.message:String(K);throw Error(`Failed to execute SQLite vector extension search for ${B}: ${M}`)}}return U.all(B).map((K)=>{let M=D(K.embedding_json),q=D(K.metadata_json);return{id:K.id,embedding:M,metadata:q,content:K.content,score:t$(M,k)}}).filter((K)=>x(K.metadata,J.filter)).sort((K,M)=>{if(M.score!==K.score)return M.score-K.score;return K.id.localeCompare(M.id)}).slice(0,J.topK)},async delete(B,k){if(G?.readOnly)throw S("vector");Z.transaction(()=>{let K=C.get(B,k),M=r();if(K&&M){let q=D(K.embedding_json).length,z=g(B,q);if(z)p(Z,z,K.rowid)}if(K&&!M){let q=D(K.embedding_json).length;l(B,q)}V.run(B,k)})()}}}export{z4 as createSQLiteVectorStore,q4 as createSQLiteSessionStore,M4 as createSQLiteDocumentStore};
function r(n){if(n===void 0)return;let e=n.trim();return e.length>0?e:void 0}function t(n){let e=n.userId.trim();if(e.length===0)throw Error("MemoryScope requires a non-empty userId");return{userId:e,tenantId:r(n.tenantId),workspaceId:r(n.workspaceId),agentId:r(n.agentId),sessionId:r(n.sessionId)}}function o(n){let e=t(n);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId??""].join("::")}function d(n){let e=t(n);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId].map((i)=>i??"").join("::")}function s(n,e){return o(n)===o(e)}
export{t as Eb,o as Fb,d as Gb,s as Hb};

Sorry, the diff of this file is too big to display

import{createRequire as k}from"node:module";var g=Object.create;var{getPrototypeOf:h,defineProperty:f,getOwnPropertyNames:i}=Object;var j=Object.prototype.hasOwnProperty;var l=(a,b,c)=>{c=a!=null?g(h(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of i(a))if(!j.call(d,e))f(d,e,{get:()=>a[e],enumerable:!0});return d};var m=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var n=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:(d)=>b[c]=()=>d})};var p=k(import.meta.url);
export{l as Kb,m as Lb,n as Mb,p as Nb};

Sorry, the diff of this file is too big to display

export type EntityKind = "proper" | "numeric";
export interface ExtractedEntity {
normalized: string;
surface: string;
kind: EntityKind;
}
/**
* Extract the salient entities from a piece of text, de-duplicated by their
* normalized key (first surface/kind wins, reading order preserved). Pure and
* deterministic.
*/
export declare function extractEntities(text: string): ExtractedEntity[];
/** The set of normalized entity keys in a piece of text. */
export declare function extractEntityKeys(text: string): Set<string>;
export interface EntityDocument {
content: string;
id: string;
}
/**
* Count, for each normalized entity key, how many documents contain it. This is
* the rarity signal the admission arm gates on: an entity present in most
* documents (e.g. a conversation's two speaker names) carries little discriminative
* value, while a rare entity strongly implicates the few facts that mention it.
* Presence is per-document (repeated mentions in one document count once).
*/
export declare function buildEntityDocumentFrequency(documents: readonly EntityDocument[]): Map<string, number>;
import type { LanguageService } from "../../language";
import type { RankedFactCandidate } from "../scoring";
export declare const TEMPORAL_INTERVAL_ANCHOR_STOPWORDS: Set<string>;
export declare const TEMPORAL_INTERVAL_ACQUISITION_OBJECT_PATTERN: RegExp;
export declare const DATE_OR_TIME_FACT_PATTERN: RegExp;
export declare const REALIZED_TEMPORAL_EVENT_FACT_PATTERN: RegExp;
export declare const HEALTH_ISSUE_EVENT_FACT_PATTERN: RegExp;
export declare const PERSONAL_WORK_CHALLENGE_STATE_PATTERN: RegExp;
export declare const PERSONAL_WORK_CONTEXT_PATTERN: RegExp;
export declare const PERSONAL_LIFE_CONTEXT_PATTERN: RegExp;
export declare const PERSONAL_WORK_CHALLENGE_RESPONSE_PATTERN: RegExp;
export declare function isTemporalIntervalQuery(query: string): boolean;
export declare function temporalIntervalAnchorFragments(query: string): string[];
export declare function temporalIntervalActionPattern(fragment: string): RegExp | undefined;
export declare function hasTemporalIntervalCredentialAcquisitionAnchor(fragment: string): boolean;
export declare function isTemporalEventOrderQuery(query: string): boolean;
export declare function isPersonalWorkChallengeEventOrderQuery(query: string): boolean;
export declare function isUserBroughtUpEventOrderQuery(query: string): boolean;
export declare function hasPersonalWorkChallengeEventSignal(entry: RankedFactCandidate): boolean;
export declare function isTemporalMostRecentQuery(query: string): boolean;
export declare function isTemporalRelativeEventQuery(query: string): boolean;
export declare function isSleepBeforeAppointmentQuery(query: string): boolean;
export declare function isTemporalIntervalEvidenceFact(entry: RankedFactCandidate): boolean;
export declare function isSourceOrderedFact(entry: RankedFactCandidate): boolean;
export declare function isTemporalOrderFact(entry: RankedFactCandidate): boolean;
export declare function temporalIntervalBoundaryPriority(input: {
content: string;
entry: RankedFactCandidate;
language: LanguageService;
query: string;
queryLocale: string;
}): number;
export declare function hasTemporalEventOrderSignal(entry: RankedFactCandidate, query: string): boolean;
export declare function temporalOrderEvidencePriority(entry: RankedFactCandidate, query?: string): number;
export declare function datedFactSortKey(entry: RankedFactCandidate): string;
export declare function sourceOrderSortKey(entry: RankedFactCandidate): number | undefined;
export declare function compareTemporalFactChronology(left: RankedFactCandidate, right: RankedFactCandidate): number;
import type { LanguageService } from "../../language";
export declare function selectorTopicTokens(text: string, language?: LanguageService, locale?: string): Set<string>;
export declare function selectorTopicOverlapCount(queryTopics: ReadonlySet<string>, factTopics: ReadonlySet<string>): number;

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display