@theokit/sdk 5.14.0 → 5.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/dist/{agent-T34LCGQM.js → agent-66U5QCPF.js} +18 -17
- package/dist/{agent-T34LCGQM.js.map → agent-66U5QCPF.js.map} +1 -1
- package/dist/{agent-DExqjqYy.d.cts → agent-BL4kxgwq.d.cts} +30 -214
- package/dist/{agent-Dfw3VsIX.d.ts → agent-ByDx7K30.d.ts} +30 -214
- package/dist/{agent-TL4K7BTG.cjs → agent-CB27KF6O.cjs} +19 -18
- package/dist/{agent-TL4K7BTG.cjs.map → agent-CB27KF6O.cjs.map} +1 -1
- package/dist/agent.d.ts +2 -3
- package/dist/{batch-EP3FCL6D.js → batch-N2XDYZED.js} +4 -4
- package/dist/{batch-EP3FCL6D.js.map → batch-N2XDYZED.js.map} +1 -1
- package/dist/{batch-IZ5EDKJ5.cjs → batch-VFR2MAUE.cjs} +7 -7
- package/dist/{batch-IZ5EDKJ5.cjs.map → batch-VFR2MAUE.cjs.map} +1 -1
- package/dist/{chunk-ZOL3L4EH.js → chunk-26GI3OYA.js} +118 -21
- package/dist/chunk-26GI3OYA.js.map +1 -0
- package/dist/{chunk-2WY2OFSC.cjs → chunk-26UQG242.cjs} +616 -318
- package/dist/chunk-26UQG242.cjs.map +1 -0
- package/dist/{chunk-2C24NSNV.js → chunk-3BBTHFGJ.js} +3 -3
- package/dist/{chunk-2C24NSNV.js.map → chunk-3BBTHFGJ.js.map} +1 -1
- package/dist/{chunk-SNVYOX46.cjs → chunk-3E3VSMB6.cjs} +160 -63
- package/dist/chunk-3E3VSMB6.cjs.map +1 -0
- package/dist/{chunk-NP362THY.cjs → chunk-3F53FLQ7.cjs} +5 -7
- package/dist/chunk-3F53FLQ7.cjs.map +1 -0
- package/dist/{chunk-SXH37C7X.cjs → chunk-55LLQFHW.cjs} +6 -6
- package/dist/{chunk-SXH37C7X.cjs.map → chunk-55LLQFHW.cjs.map} +1 -1
- package/dist/{chunk-ZJAYFSVI.js → chunk-7ACS6P5Z.js} +5 -7
- package/dist/chunk-7ACS6P5Z.js.map +1 -0
- package/dist/{chunk-WDVG5R2Q.cjs → chunk-AUH2EVWY.cjs} +4 -3
- package/dist/chunk-AUH2EVWY.cjs.map +1 -0
- package/dist/chunk-BNEUB52I.cjs +55 -0
- package/dist/chunk-BNEUB52I.cjs.map +1 -0
- package/dist/chunk-BPL5CVZ5.js +53 -0
- package/dist/chunk-BPL5CVZ5.js.map +1 -0
- package/dist/{chunk-NVQSBRG6.js → chunk-CBBT42VX.js} +3 -3
- package/dist/{chunk-NVQSBRG6.js.map → chunk-CBBT42VX.js.map} +1 -1
- package/dist/chunk-CHKV2L2Y.cjs +416 -0
- package/dist/chunk-CHKV2L2Y.cjs.map +1 -0
- package/dist/{chunk-LXG6VL6R.cjs → chunk-FBIDOOJM.cjs} +3 -3
- package/dist/{chunk-LXG6VL6R.cjs.map → chunk-FBIDOOJM.cjs.map} +1 -1
- package/dist/{chunk-354F3OF5.js → chunk-FGGVSHDW.js} +3 -3
- package/dist/{chunk-354F3OF5.js.map → chunk-FGGVSHDW.js.map} +1 -1
- package/dist/{chunk-6OCJWGVD.cjs → chunk-FTXY4D44.cjs} +4 -4
- package/dist/{chunk-6OCJWGVD.cjs.map → chunk-FTXY4D44.cjs.map} +1 -1
- package/dist/chunk-INVEGVGO.js +405 -0
- package/dist/chunk-INVEGVGO.js.map +1 -0
- package/dist/{chunk-DF77RBF4.js → chunk-LCCT5ZXJ.js} +6 -6
- package/dist/{chunk-DF77RBF4.js.map → chunk-LCCT5ZXJ.js.map} +1 -1
- package/dist/{chunk-G7XBVM3T.cjs → chunk-MHUOVS5I.cjs} +5 -5
- package/dist/{chunk-G7XBVM3T.cjs.map → chunk-MHUOVS5I.cjs.map} +1 -1
- package/dist/{chunk-CWQPQTUZ.cjs → chunk-NEH3BPFD.cjs} +15 -15
- package/dist/{chunk-CWQPQTUZ.cjs.map → chunk-NEH3BPFD.cjs.map} +1 -1
- package/dist/{chunk-5AR6O7GW.js → chunk-NK5EOTDY.js} +3 -3
- package/dist/{chunk-5AR6O7GW.js.map → chunk-NK5EOTDY.js.map} +1 -1
- package/dist/{chunk-NAVUTK6X.js → chunk-O2RCS3SJ.js} +3 -3
- package/dist/{chunk-NAVUTK6X.js.map → chunk-O2RCS3SJ.js.map} +1 -1
- package/dist/{chunk-4TEGFMSP.cjs → chunk-P7QYG4RZ.cjs} +23 -15
- package/dist/chunk-P7QYG4RZ.cjs.map +1 -0
- package/dist/chunk-PPU2D4FZ.js +19 -0
- package/dist/chunk-PPU2D4FZ.js.map +1 -0
- package/dist/{chunk-AB4OPJLD.js → chunk-RGVMJU57.js} +3 -3
- package/dist/{chunk-AB4OPJLD.js.map → chunk-RGVMJU57.js.map} +1 -1
- package/dist/{chunk-4KBI37F3.cjs → chunk-RTDVSHJR.cjs} +5 -5
- package/dist/{chunk-4KBI37F3.cjs.map → chunk-RTDVSHJR.cjs.map} +1 -1
- package/dist/{chunk-CJN5CEI3.js → chunk-RZL2W4C3.js} +23 -15
- package/dist/chunk-RZL2W4C3.js.map +1 -0
- package/dist/chunk-SPEN7RJU.cjs +18 -0
- package/dist/{chunk-R5UQL2R5.cjs.map → chunk-SPEN7RJU.cjs.map} +1 -1
- package/dist/{chunk-BZK5QL3N.cjs → chunk-TRPRTZEH.cjs} +4 -4
- package/dist/{chunk-BZK5QL3N.cjs.map → chunk-TRPRTZEH.cjs.map} +1 -1
- package/dist/{chunk-ZF2LDKQQ.cjs → chunk-U3DW3WDE.cjs} +9 -8
- package/dist/chunk-U3DW3WDE.cjs.map +1 -0
- package/dist/{chunk-H7G65PNI.js → chunk-VCQ37TC5.js} +3 -3
- package/dist/{chunk-H7G65PNI.js.map → chunk-VCQ37TC5.js.map} +1 -1
- package/dist/{chunk-3ONIVO2I.js → chunk-VNRNZ3WI.js} +3 -3
- package/dist/{chunk-3ONIVO2I.js.map → chunk-VNRNZ3WI.js.map} +1 -1
- package/dist/{chunk-SDZ4XDWS.cjs → chunk-VWYFGE27.cjs} +9 -9
- package/dist/{chunk-SDZ4XDWS.cjs.map → chunk-VWYFGE27.cjs.map} +1 -1
- package/dist/{chunk-RN3XDZGS.js → chunk-WM646HEN.js} +4 -3
- package/dist/chunk-WM646HEN.js.map +1 -0
- package/dist/chunk-X7CE7Y5W.js +305 -0
- package/dist/chunk-X7CE7Y5W.js.map +1 -0
- package/dist/{chunk-CGH4BCIY.cjs → chunk-XE3CAY6Z.cjs} +5 -5
- package/dist/{chunk-CGH4BCIY.cjs.map → chunk-XE3CAY6Z.cjs.map} +1 -1
- package/dist/chunk-XOU3CL7S.cjs +312 -0
- package/dist/chunk-XOU3CL7S.cjs.map +1 -0
- package/dist/{chunk-ULEK4OM4.js → chunk-YKNBTHMD.js} +3 -3
- package/dist/{chunk-ULEK4OM4.js.map → chunk-YKNBTHMD.js.map} +1 -1
- package/dist/{chunk-GARVAUCU.js → chunk-ZQWRUJHE.js} +534 -236
- package/dist/chunk-ZQWRUJHE.js.map +1 -0
- package/dist/{compact-session-D2MQDB6G.cjs → compact-session-CHBJOYWP.cjs} +16 -16
- package/dist/{compact-session-D2MQDB6G.cjs.map → compact-session-CHBJOYWP.cjs.map} +1 -1
- package/dist/{compact-session-N2PPHQO6.js → compact-session-F3J3FMEU.js} +7 -7
- package/dist/{compact-session-N2PPHQO6.js.map → compact-session-F3J3FMEU.js.map} +1 -1
- package/dist/{cron-CK2v0VWA.d.cts → cron-B7KH9sHW.d.cts} +2 -2
- package/dist/{cron-BubDpFJG.d.ts → cron-FEO7UAQF.d.ts} +2 -2
- package/dist/cron.cjs +18 -17
- package/dist/cron.d.cts +4 -3
- package/dist/cron.d.ts +4 -3
- package/dist/cron.js +17 -16
- package/dist/eval.cjs +17 -16
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +16 -15
- package/dist/eval.js.map +1 -1
- package/dist/fs-session-store-CYNTEPJZ.cjs +20 -0
- package/dist/{fs-session-store-S2AXVJIX.cjs.map → fs-session-store-CYNTEPJZ.cjs.map} +1 -1
- package/dist/fs-session-store-MYQEVUFL.js +11 -0
- package/dist/{fs-session-store-6ZCCJX3K.js.map → fs-session-store-MYQEVUFL.js.map} +1 -1
- package/dist/{index-manager-HO456AVW.cjs → index-manager-2KH75BRW.cjs} +7 -7
- package/dist/{index-manager-HO456AVW.cjs.map → index-manager-2KH75BRW.cjs.map} +1 -1
- package/dist/{index-manager-QDH56FER.js → index-manager-NF2WRLOU.js} +6 -6
- package/dist/{index-manager-QDH56FER.js.map → index-manager-NF2WRLOU.js.map} +1 -1
- package/dist/index.cjs +66 -262
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -46
- package/dist/index.d.ts +10 -46
- package/dist/index.js +27 -227
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-J26SHHIO.js → inject-session-LC2TROHM.js} +3 -3
- package/dist/{inject-session-J26SHHIO.js.map → inject-session-LC2TROHM.js.map} +1 -1
- package/dist/{inject-session-3ICZIJ2N.cjs → inject-session-T4RXANG3.cjs} +4 -4
- package/dist/{inject-session-3ICZIJ2N.cjs.map → inject-session-T4RXANG3.cjs.map} +1 -1
- package/dist/internal/agent-loop/doom-loop-tracker.d.ts +3 -0
- package/dist/internal/agent-loop/types.d.ts +6 -0
- package/dist/internal/error-mappers/anthropic.d.ts +3 -0
- package/dist/internal/error-mappers/openai-compatible.d.ts +2 -3
- package/dist/internal/llm/hermes-tool-extract.d.ts +2 -0
- package/dist/internal/local-agent/local-agent-dispatch.d.ts +3 -1
- package/dist/internal/local-agent/send-queue.d.ts +31 -0
- package/dist/internal/mcp/client.d.ts +2 -0
- package/dist/internal/mcp/oauth-bearer.d.ts +2 -0
- package/dist/internal/memory/adapters/index.cjs +3 -3
- package/dist/internal/memory/adapters/index.js +2 -2
- package/dist/internal/memory/dreaming/phases.d.ts +15 -0
- package/dist/internal/memory/dreaming/run.d.ts +29 -0
- package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
- package/dist/internal/memory/storage/index.cjs +51 -35
- package/dist/internal/memory/storage/index.d.cts +2 -0
- package/dist/internal/memory/storage/index.d.ts +2 -0
- package/dist/internal/memory/storage/index.js +4 -4
- package/dist/internal/persistence/cwd-mutex.d.cts +4 -2
- package/dist/internal/persistence/cwd-mutex.d.ts +4 -2
- package/dist/internal/persistence/index.cjs +4 -4
- package/dist/internal/persistence/index.js +2 -2
- package/dist/internal/persistence/sqlite-session-store.d.cts +25 -0
- package/dist/internal/persistence/sqlite-session-store.d.ts +25 -0
- package/dist/internal/providers/registry.d.ts +5 -1
- package/dist/mcp-auth.cjs +25 -307
- package/dist/mcp-auth.cjs.map +1 -1
- package/dist/mcp-auth.js +5 -305
- package/dist/mcp-auth.js.map +1 -1
- package/dist/models.cjs +9 -9
- package/dist/models.js +2 -2
- package/dist/persistence.cjs +9 -4
- package/dist/persistence.cjs.map +1 -1
- package/dist/persistence.d.cts +744 -40
- package/dist/persistence.d.ts +744 -40
- package/dist/persistence.js +3 -2
- package/dist/persistence.js.map +1 -1
- package/dist/providers.cjs +4 -4
- package/dist/providers.js +2 -2
- package/dist/sandbox/docker-sandbox.d.cts +58 -0
- package/dist/sandbox/docker-sandbox.d.ts +58 -0
- package/dist/sandbox/index.cjs +129 -1
- package/dist/sandbox/index.cjs.map +1 -1
- package/dist/sandbox/index.d.cts +1 -0
- package/dist/sandbox/index.d.ts +1 -0
- package/dist/sandbox/index.js +132 -5
- package/dist/sandbox/index.js.map +1 -1
- package/dist/{sdk-agent-DwzHcuxy.d.cts → sdk-agent-BA_6_wtc.d.cts} +30 -2
- package/dist/{sdk-agent-a3fW1xUK.d.ts → sdk-agent-CnwPODYH.d.ts} +30 -2
- package/dist/session-store-Dh07jr9N.d.cts +209 -0
- package/dist/session-store-Dh07jr9N.d.ts +209 -0
- package/dist/sqlite-session-store-BbcpKY1L.d.ts +64 -0
- package/dist/sqlite-session-store-TKXtT4ON.d.cts +64 -0
- package/dist/subagents-loader-KLWF4QPD.cjs +16 -0
- package/dist/{subagents-loader-TXOA5EJJ.cjs.map → subagents-loader-KLWF4QPD.cjs.map} +1 -1
- package/dist/subagents-loader-SXETS2F2.js +7 -0
- package/dist/{subagents-loader-Z744TAKD.js.map → subagents-loader-SXETS2F2.js.map} +1 -1
- package/dist/subagents-loader.cjs +2 -2
- package/dist/subagents-loader.d.cts +3 -2
- package/dist/subagents-loader.d.ts +3 -2
- package/dist/subagents-loader.js +1 -1
- package/dist/types/agent.d.ts +14 -1
- package/dist/types/budget-tracker.d.ts +6 -2
- package/dist/types/hooks.d.ts +7 -1
- package/dist/types/mcp.d.ts +14 -0
- package/dist/types/run.d.ts +15 -1
- package/dist/workflow.d.cts +1 -1
- package/dist/workflow.d.ts +1 -1
- package/docs/adr/mutation-testing-scope.md +12 -2
- package/docs/error-codes.md +41 -40
- package/docs/harness-capability-map.md +32 -6
- package/package.json +1 -1
- package/dist/chunk-2WY2OFSC.cjs.map +0 -1
- package/dist/chunk-4TEGFMSP.cjs.map +0 -1
- package/dist/chunk-6CXRYPG7.cjs +0 -211
- package/dist/chunk-6CXRYPG7.cjs.map +0 -1
- package/dist/chunk-CJN5CEI3.js.map +0 -1
- package/dist/chunk-GARVAUCU.js.map +0 -1
- package/dist/chunk-MSEL5E5P.js +0 -204
- package/dist/chunk-MSEL5E5P.js.map +0 -1
- package/dist/chunk-NP362THY.cjs.map +0 -1
- package/dist/chunk-Q5EWJPRY.js +0 -18
- package/dist/chunk-Q5EWJPRY.js.map +0 -1
- package/dist/chunk-R5UQL2R5.cjs +0 -18
- package/dist/chunk-RN3XDZGS.js.map +0 -1
- package/dist/chunk-SNVYOX46.cjs.map +0 -1
- package/dist/chunk-WDVG5R2Q.cjs.map +0 -1
- package/dist/chunk-ZF2LDKQQ.cjs.map +0 -1
- package/dist/chunk-ZJAYFSVI.js.map +0 -1
- package/dist/chunk-ZOL3L4EH.js.map +0 -1
- package/dist/fs-session-store-6ZCCJX3K.js +0 -11
- package/dist/fs-session-store-S2AXVJIX.cjs +0 -20
- package/dist/subagents-loader-TXOA5EJJ.cjs +0 -16
- package/dist/subagents-loader-Z744TAKD.js +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/llm/model-capabilities.ts"],"names":[],"mappings":";;;AAgCA,IAAM,qBAAA,GAA2C;AAAA,EAC/C,cAAA,EAAgB,KAAA;AAAA,EAChB,wBAAA,EAA0B,KAAA;AAAA,EAC1B,eAAA,EAAiB,KAAA;AAAA,EACjB,oBAAA,EAAsB,KAAA;AAAA,EACtB,gBAAA,EAAkB,IAAA;AAAA,EAClB,eAAA,EAAiB;AACnB,CAAA;AAGA,IAAM,gBAAA,GAAmB,CAAC,aAAA,EAAe,SAAA,EAAW,UAAU,CAAA;AAM9D,SAAS,gBAAgB,CAAA,EAAoC;AAC3D,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB,EAAE,UAAA,EAAY,KAAA,EAAO,SAAS,OAAO,CAAA,IAAK,EAAE,UAAA,IAAc,KAAA;AAAA,IAC1E,wBAAA,EAA0B,EAAE,iBAAA,IAAqB,KAAA;AAAA,IACjD,eAAA,EAAiB,EAAE,SAAA,IAAa,KAAA;AAAA,IAChC,oBAAA,EAAuB,EAAkC,aAAA,IAAiB,KAAA;AAAA,IAC1E,gBAAA,EAAkB,CAAA,CAAE,KAAA,EAAO,OAAA,IAAW,qBAAA,CAAsB,gBAAA;AAAA,IAC5D,eAAA,EAAiB,CAAA,CAAE,KAAA,EAAO,MAAA,IAAU,qBAAA,CAAsB;AAAA,GAC5D;AACF;AAWO,SAAS,yBAAyB,OAAA,EAAoC;AAC3E,EAAA,MAAM,IAAA,GAAO,kBAAA,CAAmB,kBAAA,CAAmB,OAAO,CAAC,CAAA;AAG3D,EAAA,MAAM,SAAA,GAAY,oBAAoB,IAAI,CAAA;AAC1C,EAAA,IAAI,SAAA,KAAc,MAAA,EAAW,OAAO,eAAA,CAAgB,SAAS,CAAA;AAG7D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at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\nimport { getCatalogModelInfo } from \"../providers/catalog-loader.js\";\nimport type { CatalogModel } from \"../providers/catalog-schema.js\";\n\n/** Map a catalog model block (models.dev shape) to the SDK's ModelCapabilities (M44 — catalog-backed). */\nfunction capsFromCatalog(m: CatalogModel): ModelCapabilities {\n return {\n supportsVision: m.modalities?.input?.includes(\"image\") ?? m.attachment ?? false,\n supportsStructuredOutput: m.structured_output ?? false,\n supportsToolUse: m.tool_call ?? false,\n supportsCacheControl: (m as { cache_control?: boolean }).cache_control ?? false,\n maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,\n maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens,\n };\n}\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n // M44 — the catalog model-info index replaced the hand-curated EXACT map (single source of truth; the\n // vendored provider-catalog.json carries the migrated data — parity-tested against the old map snapshot).\n const fromIndex = getCatalogModelInfo(bare);\n if (fromIndex !== undefined) return capsFromCatalog(fromIndex);\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = getCatalogModelInfo(withVendor);\n if (vendored !== undefined) return capsFromCatalog(vendored);\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\n/**\n * B-412 / B-475 — whether a model id names an Anthropic model the loop sends cacheable system\n * blocks to. Decided by the id, not by the catalog's `supportsCacheControl`, which is false for the\n * Anthropic ids measured on OpenRouter. After the same routing prefixes the capability lookup\n * strips (`openrouter/`, `vertex/`, `bedrock/`), the id must start with `anthropic/` or `claude`,\n * so Vertex Anthropic ids match and Bedrock ids (`anthropic.claude-…`) do not.\n * @internal\n */\nexport function isAnthropicFamilyModel(modelId: string | undefined): boolean {\n if (modelId === undefined) return false;\n return /^(anthropic\\/|claude)/.test(stripRoutingPrefix(modelId));\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n"]}
|
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkVWYFGE27_cjs = require('./chunk-VWYFGE27.cjs');
|
|
4
|
+
var chunkU3DW3WDE_cjs = require('./chunk-U3DW3WDE.cjs');
|
|
5
|
+
var chunkZOFRNNZD_cjs = require('./chunk-ZOFRNNZD.cjs');
|
|
6
|
+
var chunkCEGU5AVD_cjs = require('./chunk-CEGU5AVD.cjs');
|
|
7
|
+
var chunkRNXXYF22_cjs = require('./chunk-RNXXYF22.cjs');
|
|
8
|
+
var crypto = require('crypto');
|
|
9
|
+
var promises = require('fs/promises');
|
|
10
|
+
var path = require('path');
|
|
11
|
+
var fs = require('fs');
|
|
12
|
+
|
|
13
|
+
function diaryPath(root) {
|
|
14
|
+
return path.join(root, "dream-diary.md");
|
|
15
|
+
}
|
|
16
|
+
function renderDiaryEntry(entry) {
|
|
17
|
+
const stamp = new Date(entry.timestampMs).toISOString();
|
|
18
|
+
const hash = entryHash(entry).slice(0, 8);
|
|
19
|
+
return [
|
|
20
|
+
`## ${stamp}`,
|
|
21
|
+
"",
|
|
22
|
+
`- entry-hash: ${hash}`,
|
|
23
|
+
`- facts before: ${entry.factsBefore}`,
|
|
24
|
+
`- facts after: ${entry.factsAfter}`,
|
|
25
|
+
`- duplicates removed: ${entry.duplicatesRemoved}`,
|
|
26
|
+
`- clusters created: ${entry.clustersCreated}`,
|
|
27
|
+
`- notes written: ${entry.notesWritten}`,
|
|
28
|
+
""
|
|
29
|
+
].join("\n");
|
|
30
|
+
}
|
|
31
|
+
async function appendDiaryEntry(root, entry) {
|
|
32
|
+
const path = diaryPath(root);
|
|
33
|
+
let raw = "";
|
|
34
|
+
try {
|
|
35
|
+
raw = await promises.readFile(path, "utf8");
|
|
36
|
+
} catch {
|
|
37
|
+
raw = "# Dream Diary\n\n";
|
|
38
|
+
}
|
|
39
|
+
const next = `${raw.endsWith("\n") ? raw : `${raw}
|
|
40
|
+
`}${renderDiaryEntry(entry)}`;
|
|
41
|
+
await chunkZOFRNNZD_cjs.replaceFileAtomic(path, next);
|
|
42
|
+
}
|
|
43
|
+
function entryHash(entry) {
|
|
44
|
+
return crypto.createHash("sha256").update(
|
|
45
|
+
[
|
|
46
|
+
entry.factsBefore,
|
|
47
|
+
entry.factsAfter,
|
|
48
|
+
entry.duplicatesRemoved,
|
|
49
|
+
entry.clustersCreated,
|
|
50
|
+
entry.notesWritten
|
|
51
|
+
].join("|")
|
|
52
|
+
).digest("hex");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/internal/memory/dreaming/phases.ts
|
|
56
|
+
var DEFAULT_DEDUP_THRESHOLD = 0.95;
|
|
57
|
+
var DEFAULT_CLUSTER_THRESHOLD = 0.75;
|
|
58
|
+
var CONSOLIDATABLE_KINDS = /* @__PURE__ */ new Set(["project"]);
|
|
59
|
+
var ATOMIC_KINDS = /* @__PURE__ */ new Set(["user", "feedback", "reference"]);
|
|
60
|
+
function dedupPolicy(fact) {
|
|
61
|
+
if (fact.kind === void 0) return "exact";
|
|
62
|
+
if (ATOMIC_KINDS.has(fact.kind)) return "never";
|
|
63
|
+
return CONSOLIDATABLE_KINDS.has(fact.kind) ? "similar" : "never";
|
|
64
|
+
}
|
|
65
|
+
function normalizeForExactMatch(text) {
|
|
66
|
+
return text.trim().toLowerCase().replace(/\s+/g, " ").replace(/[.!?]+$/, "");
|
|
67
|
+
}
|
|
68
|
+
async function lightPhase(facts, embedding, threshold = DEFAULT_DEDUP_THRESHOLD) {
|
|
69
|
+
if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };
|
|
70
|
+
const never = facts.filter((f) => dedupPolicy(f) === "never");
|
|
71
|
+
const exact = facts.filter((f) => dedupPolicy(f) === "exact");
|
|
72
|
+
const similar = facts.filter((f) => dedupPolicy(f) === "similar");
|
|
73
|
+
const seen = /* @__PURE__ */ new Set();
|
|
74
|
+
const exactKept = [];
|
|
75
|
+
let removed = 0;
|
|
76
|
+
for (const f of exact) {
|
|
77
|
+
const key = normalizeForExactMatch(f.text);
|
|
78
|
+
if (seen.has(key)) {
|
|
79
|
+
removed += 1;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
seen.add(key);
|
|
83
|
+
exactKept.push(f);
|
|
84
|
+
}
|
|
85
|
+
const sim = similar.length > 1 ? await dedupCandidates(similar, embedding, threshold) : { kept: [...similar], duplicatesRemoved: 0 };
|
|
86
|
+
return {
|
|
87
|
+
kept: [...never, ...exactKept, ...sim.kept],
|
|
88
|
+
duplicatesRemoved: removed + sim.duplicatesRemoved
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
async function dedupCandidates(facts, embedding, threshold) {
|
|
92
|
+
if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };
|
|
93
|
+
const vectors = await embedding.embed(facts.map((f) => f.text));
|
|
94
|
+
const keptIdx = [];
|
|
95
|
+
const keptVecs = [];
|
|
96
|
+
for (let i = 0; i < facts.length; i++) {
|
|
97
|
+
const vec = vectors[i] ?? [];
|
|
98
|
+
const isDup = keptVecs.some((kept2) => cosineSimilarity(vec, kept2) >= threshold);
|
|
99
|
+
if (isDup) continue;
|
|
100
|
+
keptIdx.push(i);
|
|
101
|
+
keptVecs.push(vec);
|
|
102
|
+
}
|
|
103
|
+
const kept = keptIdx.map((i) => facts[i]);
|
|
104
|
+
return { kept, duplicatesRemoved: facts.length - kept.length };
|
|
105
|
+
}
|
|
106
|
+
var DEFAULT_MAX_FACTS_PER_SWEEP = 500;
|
|
107
|
+
async function remPhase(facts, embedding, threshold = DEFAULT_CLUSTER_THRESHOLD, maxFactsPerSweep = DEFAULT_MAX_FACTS_PER_SWEEP) {
|
|
108
|
+
if (facts.length === 0) return { clusters: [], factsLeftOut: 0 };
|
|
109
|
+
const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;
|
|
110
|
+
const vectors = await embedding.embed(capped.map((f) => f.text));
|
|
111
|
+
const clusterOfIdx = unionFindByPairs(vectors, threshold);
|
|
112
|
+
const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);
|
|
113
|
+
return {
|
|
114
|
+
clusters: [...groups.values()].map(buildClusterFromMembers),
|
|
115
|
+
factsLeftOut: facts.length - capped.length
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function unionFindByPairs(vectors, threshold) {
|
|
119
|
+
const clusterOfIdx = vectors.map((_, i) => i);
|
|
120
|
+
for (let i = 0; i < vectors.length; i++) {
|
|
121
|
+
for (let j = i + 1; j < vectors.length; j++) {
|
|
122
|
+
if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {
|
|
123
|
+
unifyClusters(clusterOfIdx, i, j);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return clusterOfIdx;
|
|
128
|
+
}
|
|
129
|
+
function bucketFactsByClusterRoot(facts, clusterOfIdx) {
|
|
130
|
+
const groups = /* @__PURE__ */ new Map();
|
|
131
|
+
for (let i = 0; i < facts.length; i++) {
|
|
132
|
+
const root = findRoot(clusterOfIdx, i);
|
|
133
|
+
const list = groups.get(root) ?? [];
|
|
134
|
+
list.push(facts[i]);
|
|
135
|
+
groups.set(root, list);
|
|
136
|
+
}
|
|
137
|
+
return groups;
|
|
138
|
+
}
|
|
139
|
+
function buildClusterFromMembers(members) {
|
|
140
|
+
const sorted = [...members].sort((a, b) => b.text.length - a.text.length);
|
|
141
|
+
return { representativeText: sorted[0]?.text ?? "", members };
|
|
142
|
+
}
|
|
143
|
+
function deepPhase(clusters, timestampMs) {
|
|
144
|
+
if (clusters.length === 0) return "";
|
|
145
|
+
const isoStamp = new Date(timestampMs).toISOString();
|
|
146
|
+
const lines = [`# Dreamed ${isoStamp}`, ""];
|
|
147
|
+
for (let i = 0; i < clusters.length; i++) {
|
|
148
|
+
const c = clusters[i];
|
|
149
|
+
if (c === void 0) continue;
|
|
150
|
+
lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);
|
|
151
|
+
lines.push("");
|
|
152
|
+
for (const member of c.members) lines.push(`- ${member.text}`);
|
|
153
|
+
lines.push("");
|
|
154
|
+
}
|
|
155
|
+
return `${lines.join("\n")}
|
|
156
|
+
`;
|
|
157
|
+
}
|
|
158
|
+
function cosineSimilarity(a, b) {
|
|
159
|
+
if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;
|
|
160
|
+
let dot = 0;
|
|
161
|
+
let aNorm = 0;
|
|
162
|
+
let bNorm = 0;
|
|
163
|
+
for (let i = 0; i < a.length; i++) {
|
|
164
|
+
const ai = a[i] ?? 0;
|
|
165
|
+
const bi = b[i] ?? 0;
|
|
166
|
+
dot += ai * bi;
|
|
167
|
+
aNorm += ai * ai;
|
|
168
|
+
bNorm += bi * bi;
|
|
169
|
+
}
|
|
170
|
+
const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);
|
|
171
|
+
return denom === 0 ? 0 : dot / denom;
|
|
172
|
+
}
|
|
173
|
+
function findRoot(parents, i) {
|
|
174
|
+
let root = i;
|
|
175
|
+
while (parents[root] !== root) {
|
|
176
|
+
const next = parents[root] ?? root;
|
|
177
|
+
if (next === root) break;
|
|
178
|
+
root = next;
|
|
179
|
+
}
|
|
180
|
+
parents[i] = root;
|
|
181
|
+
return root;
|
|
182
|
+
}
|
|
183
|
+
function unifyClusters(parents, a, b) {
|
|
184
|
+
const rootA = findRoot(parents, a);
|
|
185
|
+
const rootB = findRoot(parents, b);
|
|
186
|
+
if (rootA !== rootB) parents[rootB] = rootA;
|
|
187
|
+
}
|
|
188
|
+
function runDreamingSweep(options) {
|
|
189
|
+
return chunkU3DW3WDE_cjs.withCwdMutex(`dream:${options.cwd}`, () => runInner(options));
|
|
190
|
+
}
|
|
191
|
+
async function runInner(options) {
|
|
192
|
+
const now = options.now ?? Date.now;
|
|
193
|
+
const timestampMs = now();
|
|
194
|
+
try {
|
|
195
|
+
const root = options.memoryRoot ?? chunkVWYFGE27_cjs.resolveMemoryRoot(options.cwd);
|
|
196
|
+
const facts = await chunkVWYFGE27_cjs.readFactsFromMarkdown(
|
|
197
|
+
options.cwd,
|
|
198
|
+
options.memoryRoot ? { directory: options.memoryRoot } : void 0
|
|
199
|
+
);
|
|
200
|
+
if (facts.length === 0) {
|
|
201
|
+
return emptyResult("skipped");
|
|
202
|
+
}
|
|
203
|
+
const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);
|
|
204
|
+
const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);
|
|
205
|
+
const notesWritten = await writeConsolidatedNotes(root, rem.clusters, timestampMs);
|
|
206
|
+
const result = {
|
|
207
|
+
status: "ok",
|
|
208
|
+
factsBefore: facts.length,
|
|
209
|
+
factsAfter: dedup.kept.length,
|
|
210
|
+
duplicatesRemoved: dedup.duplicatesRemoved,
|
|
211
|
+
clustersCreated: rem.clusters.length,
|
|
212
|
+
notesWritten,
|
|
213
|
+
diaryEntryHash: void 0,
|
|
214
|
+
factsLeftOut: rem.factsLeftOut
|
|
215
|
+
};
|
|
216
|
+
await appendDiaryEntry(root, {
|
|
217
|
+
timestampMs,
|
|
218
|
+
factsBefore: result.factsBefore,
|
|
219
|
+
factsAfter: result.factsAfter,
|
|
220
|
+
duplicatesRemoved: result.duplicatesRemoved,
|
|
221
|
+
clustersCreated: result.clustersCreated,
|
|
222
|
+
notesWritten: result.notesWritten
|
|
223
|
+
});
|
|
224
|
+
return result;
|
|
225
|
+
} catch (cause) {
|
|
226
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
227
|
+
chunkRNXXYF22_cjs.diag(`[theokit-sdk] dreaming sweep failed: ${message}
|
|
228
|
+
`);
|
|
229
|
+
return emptyResult("error");
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
async function writeConsolidatedNotes(root, clusters, timestampMs) {
|
|
233
|
+
if (clusters.length === 0) return 0;
|
|
234
|
+
const notesDir = path.join(root, "notes");
|
|
235
|
+
await promises.mkdir(notesDir, { recursive: true });
|
|
236
|
+
const isoSlug = new Date(timestampMs).toISOString().replace(/[^\dT]/g, "-");
|
|
237
|
+
const file = path.join(notesDir, `dreamed-${isoSlug}.md`);
|
|
238
|
+
const body = deepPhase(clusters, timestampMs);
|
|
239
|
+
await chunkZOFRNNZD_cjs.replaceFileAtomic(file, body);
|
|
240
|
+
return 1;
|
|
241
|
+
}
|
|
242
|
+
function emptyResult(status) {
|
|
243
|
+
const result = {
|
|
244
|
+
status,
|
|
245
|
+
factsBefore: 0,
|
|
246
|
+
factsAfter: 0,
|
|
247
|
+
duplicatesRemoved: 0,
|
|
248
|
+
clustersCreated: 0,
|
|
249
|
+
notesWritten: 0,
|
|
250
|
+
diaryEntryHash: void 0
|
|
251
|
+
};
|
|
252
|
+
return status === "skipped" ? { ...result, factsLeftOut: 0 } : result;
|
|
253
|
+
}
|
|
254
|
+
async function readAllSqliteFacts(root) {
|
|
255
|
+
const dbPath = chunkVWYFGE27_cjs.defaultIndexPath(root);
|
|
256
|
+
if (!fs.existsSync(dbPath)) return [];
|
|
257
|
+
const db = await chunkVWYFGE27_cjs.openMemoryDb({ filePath: dbPath });
|
|
258
|
+
try {
|
|
259
|
+
const stmt = db.prepare("SELECT id, path, source, start_line, end_line, text FROM chunks");
|
|
260
|
+
const rows = stmt.all();
|
|
261
|
+
return rows.map((r) => ({
|
|
262
|
+
...r,
|
|
263
|
+
namespace: "default",
|
|
264
|
+
scope: "agent",
|
|
265
|
+
user_id: "default"
|
|
266
|
+
}));
|
|
267
|
+
} finally {
|
|
268
|
+
db.close();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
function nfcEqual(a, b) {
|
|
272
|
+
return a.normalize("NFC") === b.normalize("NFC");
|
|
273
|
+
}
|
|
274
|
+
function assertUsableBatchSize(batchSize) {
|
|
275
|
+
if (batchSize === void 0) return;
|
|
276
|
+
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
|
277
|
+
throw new chunkCEGU5AVD_cjs.ConfigurationError(
|
|
278
|
+
`migrateSqliteToLance: batchSize must be a whole number of at least 1; received ${String(batchSize)}.`,
|
|
279
|
+
{ code: "invalid_batch_size" }
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
async function migrateSqliteToLance(opts) {
|
|
284
|
+
assertUsableBatchSize(opts.batchSize);
|
|
285
|
+
const cwd = opts.cwd;
|
|
286
|
+
const memoryRoot = chunkVWYFGE27_cjs.resolveMemoryRoot(cwd, { directory: opts.directory });
|
|
287
|
+
const finalPath = chunkVWYFGE27_cjs.lanceStoragePath(memoryRoot);
|
|
288
|
+
const newPath = path.join(memoryRoot, "lance-new");
|
|
289
|
+
const rawLog = opts.logger ?? ((m) => console.log(m));
|
|
290
|
+
const log = (m) => rawLog(chunkRNXXYF22_cjs.redactSecrets(m));
|
|
291
|
+
if (fs.existsSync(finalPath)) {
|
|
292
|
+
throw new chunkCEGU5AVD_cjs.ConfigurationError(
|
|
293
|
+
`Destination already exists: ${finalPath}. Remove it manually (\`rm -rf ${finalPath}\`) and re-run.`,
|
|
294
|
+
{ code: "migration_destination_exists" }
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
if (fs.existsSync(newPath)) {
|
|
298
|
+
log(`Removing stale ${newPath} from a previous run...`);
|
|
299
|
+
fs.rmSync(newPath, { recursive: true, force: true });
|
|
300
|
+
}
|
|
301
|
+
log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);
|
|
302
|
+
const sqliteFacts = await readAllSqliteFacts(memoryRoot);
|
|
303
|
+
log(`SQLite has ${sqliteFacts.length} facts.`);
|
|
304
|
+
if (sqliteFacts.length === 0) {
|
|
305
|
+
return {
|
|
306
|
+
countSqlite: 0,
|
|
307
|
+
countLance: 0,
|
|
308
|
+
validated: true,
|
|
309
|
+
sampleComparisons: [],
|
|
310
|
+
lancePath: finalPath,
|
|
311
|
+
committed: false
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
const placeholderEmbedding = {
|
|
315
|
+
id: "migration-placeholder",
|
|
316
|
+
model: "deterministic-hash",
|
|
317
|
+
dimension: 8,
|
|
318
|
+
embed: async (texts) => {
|
|
319
|
+
return texts.map((t) => {
|
|
320
|
+
const arr = new Array(8).fill(0);
|
|
321
|
+
for (let i = 0; i < t.length; i += 1) {
|
|
322
|
+
arr[i % 8] += t.charCodeAt(i);
|
|
323
|
+
}
|
|
324
|
+
return arr.map((x) => x / 1e3);
|
|
325
|
+
});
|
|
326
|
+
},
|
|
327
|
+
stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 })
|
|
328
|
+
};
|
|
329
|
+
fs.mkdirSync(newPath, { recursive: true });
|
|
330
|
+
log(`Writing Lance index to ${newPath} ...`);
|
|
331
|
+
const lance = await chunkVWYFGE27_cjs.LanceIndex.open({
|
|
332
|
+
cwd,
|
|
333
|
+
embedding: placeholderEmbedding,
|
|
334
|
+
storagePath: newPath
|
|
335
|
+
});
|
|
336
|
+
const batchSize = opts.batchSize ?? 100;
|
|
337
|
+
for (let i = 0; i < sqliteFacts.length; i += batchSize) {
|
|
338
|
+
const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({
|
|
339
|
+
id: f.id,
|
|
340
|
+
text: f.text,
|
|
341
|
+
source: f.source,
|
|
342
|
+
namespace: f.namespace ?? "default",
|
|
343
|
+
scope: f.scope ?? "agent",
|
|
344
|
+
user_id: f.user_id ?? "default",
|
|
345
|
+
timestamp: 0
|
|
346
|
+
}));
|
|
347
|
+
await lance.addFacts(batch);
|
|
348
|
+
log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);
|
|
349
|
+
}
|
|
350
|
+
const lanceCount = await lance.countFacts("default");
|
|
351
|
+
log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);
|
|
352
|
+
const sampleSize = Math.min(10, sqliteFacts.length);
|
|
353
|
+
const sampleComparisons = [];
|
|
354
|
+
for (let i = 0; i < sampleSize; i += 1) {
|
|
355
|
+
const sqliteFact = sqliteFacts[Math.floor(i * sqliteFacts.length / sampleSize)];
|
|
356
|
+
if (sqliteFact === void 0) continue;
|
|
357
|
+
const hits = await lance.search(sqliteFact.text, {
|
|
358
|
+
namespace: sqliteFact.namespace ?? "default",
|
|
359
|
+
limit: 1
|
|
360
|
+
});
|
|
361
|
+
const hit = hits[0];
|
|
362
|
+
const match = hit !== void 0 && nfcEqual(hit.text, sqliteFact.text);
|
|
363
|
+
sampleComparisons.push({ id: sqliteFact.id, match });
|
|
364
|
+
}
|
|
365
|
+
const allMatch = sampleComparisons.every((c) => c.match);
|
|
366
|
+
const countMatch = lanceCount === sqliteFacts.length;
|
|
367
|
+
const validated = allMatch && countMatch;
|
|
368
|
+
await lance.close();
|
|
369
|
+
if (opts.dryRun === true) {
|
|
370
|
+
log("Dry-run mode \u2014 discarding Lance staging dir.");
|
|
371
|
+
fs.rmSync(newPath, { recursive: true, force: true });
|
|
372
|
+
return {
|
|
373
|
+
countSqlite: sqliteFacts.length,
|
|
374
|
+
countLance: lanceCount,
|
|
375
|
+
validated,
|
|
376
|
+
sampleComparisons,
|
|
377
|
+
lancePath: finalPath,
|
|
378
|
+
committed: false
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
if (!validated) {
|
|
382
|
+
log("Validation FAILED \u2014 leaving SQLite intact, removing Lance staging dir.");
|
|
383
|
+
fs.rmSync(newPath, { recursive: true, force: true });
|
|
384
|
+
return {
|
|
385
|
+
countSqlite: sqliteFacts.length,
|
|
386
|
+
countLance: lanceCount,
|
|
387
|
+
validated: false,
|
|
388
|
+
sampleComparisons,
|
|
389
|
+
lancePath: finalPath,
|
|
390
|
+
committed: false
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
fs.renameSync(newPath, finalPath);
|
|
394
|
+
log(`Migration committed to ${finalPath}.`);
|
|
395
|
+
return {
|
|
396
|
+
countSqlite: sqliteFacts.length,
|
|
397
|
+
countLance: lanceCount,
|
|
398
|
+
validated: true,
|
|
399
|
+
sampleComparisons,
|
|
400
|
+
lancePath: finalPath,
|
|
401
|
+
committed: true
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
exports.appendDiaryEntry = appendDiaryEntry;
|
|
406
|
+
exports.deepPhase = deepPhase;
|
|
407
|
+
exports.diaryPath = diaryPath;
|
|
408
|
+
exports.entryHash = entryHash;
|
|
409
|
+
exports.lightPhase = lightPhase;
|
|
410
|
+
exports.migrateSqliteToLance = migrateSqliteToLance;
|
|
411
|
+
exports.readAllSqliteFacts = readAllSqliteFacts;
|
|
412
|
+
exports.remPhase = remPhase;
|
|
413
|
+
exports.renderDiaryEntry = renderDiaryEntry;
|
|
414
|
+
exports.runDreamingSweep = runDreamingSweep;
|
|
415
|
+
//# sourceMappingURL=chunk-CHKV2L2Y.cjs.map
|
|
416
|
+
//# sourceMappingURL=chunk-CHKV2L2Y.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/memory/dreaming/diary.ts","../src/internal/memory/dreaming/phases.ts","../src/internal/memory/dreaming/run.ts","../src/internal/memory/migrate-sqlite-to-lance.ts"],"names":["join","readFile","replaceFileAtomic","createHash","kept","withCwdMutex","resolveMemoryRoot","readFactsFromMarkdown","diag","mkdir","defaultIndexPath","existsSync","openMemoryDb","ConfigurationError","lanceStoragePath","redactSecrets","rmSync","mkdirSync","LanceIndex","renameSync"],"mappings":";;;;;;;;;;;;AA6BO,SAAS,UAAU,IAAA,EAA0B;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{ readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport type { MemoryRoot } from \"../storage/memory-root.js\";\n\n/**\n * Dream-diary append (ADR D7).\n *\n * Diary lives at `.theokit/memory/dream-diary.md` and grows with one entry\n * per sweep. Each entry is content-hashed so the same input produces the\n * same entry — idempotency contract.\n *\n * Writes go through `replaceFileAtomic` (EC-3 of edge-case review) so a\n * crash mid-write can never leave a half-written diary.\n *\n * Shared with `@theokit/sdk-memory`; see the memory-store barrel.\n */\n\nexport interface DiaryEntry {\n timestampMs: number;\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}\n\n/** `<memory root>/dream-diary.md`. Takes the RESOLVED ROOT — see `storage/memory-root.ts` (#463). */\nexport function diaryPath(root: MemoryRoot): string {\n return join(root, \"dream-diary.md\");\n}\n\n/**\n * One diary entry as the markdown that gets appended: a timestamp heading, the short entry hash,\n * and the counts the sweep produced. The hash is what makes a re-run recognisable as the same\n * sweep rather than a new one.\n */\nexport function renderDiaryEntry(entry: DiaryEntry): string {\n const stamp = new Date(entry.timestampMs).toISOString();\n const hash = entryHash(entry).slice(0, 8);\n return [\n `## ${stamp}`,\n \"\",\n `- entry-hash: ${hash}`,\n `- facts before: ${entry.factsBefore}`,\n `- facts after: ${entry.factsAfter}`,\n `- duplicates removed: ${entry.duplicatesRemoved}`,\n `- clusters created: ${entry.clustersCreated}`,\n `- notes written: ${entry.notesWritten}`,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Append one sweep's entry to `<memory root>/dream-diary.md`, creating the file with its header\n * when this is the first sweep. The diary is a human-readable record of what dreaming changed —\n * consolidations are otherwise invisible, because they alter the notes rather than announce\n * themselves.\n */\nexport async function appendDiaryEntry(root: MemoryRoot, entry: DiaryEntry): Promise<void> {\n const path = diaryPath(root);\n let raw = \"\";\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n raw = \"# Dream Diary\\n\\n\";\n }\n const next = `${raw.endsWith(\"\\n\") ? raw : `${raw}\\n`}${renderDiaryEntry(entry)}`;\n await replaceFileAtomic(path, next);\n}\n\n/**\n * A stable hash of one entry's counts, so two sweeps that did the same work read as the same work.\n * Rendered truncated in the entry; the full value is what callers compare.\n */\nexport function entryHash(entry: DiaryEntry): string {\n return createHash(\"sha256\")\n .update(\n [\n entry.factsBefore,\n entry.factsAfter,\n entry.duplicatesRemoved,\n entry.clustersCreated,\n entry.notesWritten,\n ].join(\"|\"),\n )\n .digest(\"hex\");\n}\n","import type { EmbeddingRuntime } from \"../embedding-adapter.js\";\nimport type { MemoryFact, MemoryKind } from \"../types.js\";\n\n/**\n * Dreaming/REM phase logic.\n *\n * Three phases:\n * - **light** — drop near-duplicate facts (cosine similarity > 0.95).\n * - **REM** — cluster thematically related facts (cosine ≥ 0.75).\n * - **deep** — pick a representative bullet per cluster (longest text\n * wins) and emit consolidated markdown notes.\n */\n\nexport interface DedupResult {\n kept: MemoryFact[];\n duplicatesRemoved: number;\n}\n\n/** A group of semantically similar facts, with the text chosen to represent them. */\nexport interface Cluster {\n representativeText: string;\n members: ReadonlyArray<MemoryFact>;\n}\n\n/** What clustering produced: the clusters and how many facts the per-sweep cap left out. */\nexport interface ClusterResult {\n clusters: Cluster[];\n /** How many input facts past the per-sweep cap were not clustered; 0 when none were. */\n factsLeftOut: number;\n}\n\nconst DEFAULT_DEDUP_THRESHOLD = 0.95;\nconst DEFAULT_CLUSTER_THRESHOLD = 0.75;\n\n/**\n * Kinds a sweep may consolidate. ADR-14 partitions the vocabulary into three buckets and only\n * this one is a merge candidate; the rest are protected for a reason that survives the sweep\n * being non-destructive.\n *\n * `user`, `feedback` and `reference` are ATOMIC: there is nothing to merge and the loss is\n * irreversible. Two corrections a user gave on different days can read alike and are not the\n * same correction. An untyped fact is protected too — a kind that nobody declared is not a\n * licence to treat it as consolidatable.\n *\n * Why this matters even though nothing is deleted: dedup drops the near-duplicate from the\n * CLUSTERING INPUT, and the cluster's representative is what the search index returns. The\n * source file survives; the artefact the agent reads does not. That is ADR-14's third rule —\n * the invariant is about what the agent reads, not what survives on disk.\n */\n// Typed against `MemoryKind` rather than `string`, so the compiler checks these against the vocabulary\n// they mirror. They were `Set<string>` and CONSOLIDATABLE_KINDS held \"session\" — not a member of\n// `MemoryKind`, and rejected by `markdown-store.assertWritable` before any fact is written, so no\n// fact reaching this policy could ever carry it. The arm read as though sessions were consolidatable\n// while no session could exist. Adding a member to either set is now a type error unless `MemoryKind`\n// gains it deliberately.\nconst CONSOLIDATABLE_KINDS: ReadonlySet<MemoryKind> = new Set([\"project\"]);\nconst ATOMIC_KINDS: ReadonlySet<MemoryKind> = new Set([\"user\", \"feedback\", \"reference\"]);\n\n/**\n * Three levels, graded by how much the store knows about the entry. The middle one exists\n * because the first draft of this filter did not have it and broke the common case.\n *\n * - ATOMIC (`user`, `feedback`, `reference`) — never deduplicated. Two corrections given on\n * different days can read alike and are not the same correction.\n * - CONSOLIDATABLE (`project`, `session`) — near-duplicate dedup at the similarity threshold.\n * Overlapping project facts are exactly what a sweep is for.\n * - UNTYPED — EXACT duplicates only. A hand-written bullet under `## Facts` carries no kind,\n * and the store's own header invites editing those by hand, so untyped is the common case\n * rather than an edge one. Treating it as atomic would disable the sweep for most stores;\n * treating it as consolidatable would let a near-duplicate of an untyped correction be\n * dropped. Exact-match is the only claim the store can make without inferring a kind, which\n * is the rule this codebase already applies one field over.\n */\ntype DedupPolicy = \"never\" | \"exact\" | \"similar\";\n\nfunction dedupPolicy(fact: MemoryFact): DedupPolicy {\n if (fact.kind === undefined) return \"exact\";\n if (ATOMIC_KINDS.has(fact.kind)) return \"never\";\n return CONSOLIDATABLE_KINDS.has(fact.kind) ? \"similar\" : \"never\";\n}\n\n/** Whitespace and case collapsed; nothing else. Not a similarity measure — an identity one. */\nfunction normalizeForExactMatch(text: string): string {\n return text\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/[.!?]+$/, \"\");\n}\n\n/**\n * Light phase — drop facts whose embedding is too similar to one already kept.\n *\n * Protected kinds bypass deduplication entirely and are returned untouched, so a sweep can\n * never conflate two of them into one representative.\n *\n * \"Drop\" here means DROPPED FROM THE RETURNED LIST. Nothing on disk is deleted, by any phase of\n * this sweep, today.\n *\n * BEFORE YOU ADD PRUNING HERE, READ THIS. The security contract for this store requires a backup\n * to precede any destructive operation (SOP-06-05 step 7). That requirement is currently LATENT\n * — not satisfied, not waived — precisely because the sweep only ever adds notes and filters a\n * list. There is no backup implementation in this package, and an audit that looked for one\n * recorded its absence as having no present consequence.\n *\n * The first commit that makes this sweep delete a file from disk is the commit that makes the\n * gap real, and it is also the commit whose author will have no reason to know this line exists.\n * That is why the trigger is written beside the code that would trip it rather than in the audit\n * that found it: a gap recorded in a reviewer's file reappears as a surprise; a gap recorded\n * here stops the person adding pruning.\n */\nexport async function lightPhase(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number = DEFAULT_DEDUP_THRESHOLD,\n): Promise<DedupResult> {\n if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };\n const never = facts.filter((f) => dedupPolicy(f) === \"never\");\n const exact = facts.filter((f) => dedupPolicy(f) === \"exact\");\n const similar = facts.filter((f) => dedupPolicy(f) === \"similar\");\n\n // Exact pass: identity, not similarity. No embedding call, no threshold, no judgement.\n const seen = new Set<string>();\n const exactKept: MemoryFact[] = [];\n let removed = 0;\n for (const f of exact) {\n const key = normalizeForExactMatch(f.text);\n if (seen.has(key)) {\n removed += 1;\n continue;\n }\n seen.add(key);\n exactKept.push(f);\n }\n\n const sim =\n similar.length > 1\n ? await dedupCandidates(similar, embedding, threshold)\n : { kept: [...similar], duplicatesRemoved: 0 };\n\n // Protected facts keep their original relative position at the front: they were never in\n // the running, and putting them back through the sort would imply they had been judged.\n return {\n kept: [...never, ...exactKept, ...sim.kept],\n duplicatesRemoved: removed + sim.duplicatesRemoved,\n };\n}\n\nasync function dedupCandidates(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number,\n): Promise<DedupResult> {\n if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };\n const vectors = await embedding.embed(facts.map((f) => f.text));\n const keptIdx: number[] = [];\n const keptVecs: number[][] = [];\n for (let i = 0; i < facts.length; i++) {\n const vec = vectors[i] ?? [];\n const isDup = keptVecs.some((kept) => cosineSimilarity(vec, kept) >= threshold);\n if (isDup) continue;\n keptIdx.push(i);\n keptVecs.push(vec);\n }\n const kept = keptIdx.map((i) => facts[i] as MemoryFact);\n return { kept, duplicatesRemoved: facts.length - kept.length };\n}\n\n// T4.6 — cap facts per sweep to prevent O(N²) blowup. 500 facts →\n// 125K comparisons (acceptable). 5000 facts → 12.5M (unacceptable).\n// When facts exceed the cap, a deterministic subsample is taken so the\n// sweep is bounded. The remaining facts are carried to the next sweep.\nconst DEFAULT_MAX_FACTS_PER_SWEEP = 500;\n\n/** REM phase — single-link agglomerative clustering by cosine similarity. */\nexport async function remPhase(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number = DEFAULT_CLUSTER_THRESHOLD,\n maxFactsPerSweep: number = DEFAULT_MAX_FACTS_PER_SWEEP,\n): Promise<ClusterResult> {\n // KNOWN GAP, deliberately not closed here. Protected kinds are excluded from DEDUP — a\n // near-duplicate correction is never dropped — but they still reach CLUSTERING, and a cluster\n // carries one representative into the consolidated note.\n //\n // Filtering them out here too was tried and reverted: untyped is the common case (hand-written\n // bullets carry no kind), so excluding it disables consolidation for most stores, and it broke\n // three existing golden tests. The damage is also smaller than in the dedup case — the source\n // files survive and remain readable, so what a cluster costs is nuance in an ADDITIONAL\n // artefact rather than a lost entry.\n //\n // It becomes real damage only if recall serves notes INSTEAD of sources. That depends on what\n // the index covers, which is not settled here. Recorded rather than silently accepted.\n if (facts.length === 0) return { clusters: [], factsLeftOut: 0 };\n // T4.6 — cap: subsample when facts exceed budget. Deterministic\n // sort by text hash so the same input always picks the same subset.\n const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;\n const vectors = await embedding.embed(capped.map((f) => f.text));\n const clusterOfIdx = unionFindByPairs(vectors, threshold);\n const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);\n return {\n clusters: [...groups.values()].map(buildClusterFromMembers),\n factsLeftOut: facts.length - capped.length,\n };\n}\n\nfunction unionFindByPairs(\n vectors: ReadonlyArray<ReadonlyArray<number>>,\n threshold: number,\n): number[] {\n const clusterOfIdx = vectors.map((_, i) => i);\n for (let i = 0; i < vectors.length; i++) {\n for (let j = i + 1; j < vectors.length; j++) {\n if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {\n unifyClusters(clusterOfIdx, i, j);\n }\n }\n }\n return clusterOfIdx;\n}\n\nfunction bucketFactsByClusterRoot(\n facts: ReadonlyArray<MemoryFact>,\n clusterOfIdx: number[],\n): Map<number, MemoryFact[]> {\n const groups = new Map<number, MemoryFact[]>();\n for (let i = 0; i < facts.length; i++) {\n const root = findRoot(clusterOfIdx, i);\n const list = groups.get(root) ?? [];\n list.push(facts[i] as MemoryFact);\n groups.set(root, list);\n }\n return groups;\n}\n\nfunction buildClusterFromMembers(members: ReadonlyArray<MemoryFact>): Cluster {\n const sorted = [...members].sort((a, b) => b.text.length - a.text.length);\n return { representativeText: sorted[0]?.text ?? \"\", members };\n}\n\n/** Deep phase — render consolidated markdown for the dreamed note. */\nexport function deepPhase(clusters: ReadonlyArray<Cluster>, timestampMs: number): string {\n if (clusters.length === 0) return \"\";\n const isoStamp = new Date(timestampMs).toISOString();\n const lines: string[] = [`# Dreamed ${isoStamp}`, \"\"];\n for (let i = 0; i < clusters.length; i++) {\n const c = clusters[i];\n if (c === undefined) continue;\n lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);\n lines.push(\"\");\n for (const member of c.members) lines.push(`- ${member.text}`);\n lines.push(\"\");\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction cosineSimilarity(a: ReadonlyArray<number>, b: ReadonlyArray<number>): number {\n if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;\n let dot = 0;\n let aNorm = 0;\n let bNorm = 0;\n for (let i = 0; i < a.length; i++) {\n const ai = a[i] ?? 0;\n const bi = b[i] ?? 0;\n dot += ai * bi;\n aNorm += ai * ai;\n bNorm += bi * bi;\n }\n const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);\n return denom === 0 ? 0 : dot / denom;\n}\n\nfunction findRoot(parents: number[], i: number): number {\n let root = i;\n while (parents[root] !== root) {\n const next = parents[root] ?? root;\n if (next === root) break;\n root = next;\n }\n parents[i] = root;\n return root;\n}\n\nfunction unifyClusters(parents: number[], a: number, b: number): void {\n const rootA = findRoot(parents, a);\n const rootB = findRoot(parents, b);\n if (rootA !== rootB) parents[rootB] = rootA;\n}\n","import { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { diag } from \"../../diagnostics.js\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport { withCwdMutex } from \"../../persistence/cwd-mutex.js\";\nimport type { EmbeddingRuntime } from \"../embedding-adapter.js\";\nimport { readFactsFromMarkdown } from \"../storage/markdown-store.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"../storage/memory-root.js\";\nimport { appendDiaryEntry } from \"./diary.js\";\nimport { deepPhase, lightPhase, remPhase } from \"./phases.js\";\n\n/**\n * Dreaming sweep orchestrator (ADR D7 of memory-system-peer-project-parity).\n *\n * Phases:\n * 1. **light** — drop near-duplicate facts via cosine similarity.\n * 2. **REM** — cluster thematically related facts.\n * 3. **deep** — write a `notes/dreamed-<ts>.md` per sweep with consolidated\n * clusters; append a diary entry.\n *\n * All file writes go through `replaceFileAtomic` (EC-3) and the entire sweep\n * holds the per-cwd mutex so a `Remember:` append can't race it.\n */\n\nexport interface DreamingOptions {\n cwd: string;\n /**\n * The memory root to sweep. Defaults to the project store — right for a caller with no\n * `memory.directory`, and wrong for one that has it, which is why it is passable (#463).\n */\n memoryRoot?: MemoryRoot;\n embedding: EmbeddingRuntime;\n dedupThreshold?: number;\n clusterThreshold?: number;\n /** Test hook — fixed timestamp for the run. */\n now?: () => number;\n}\n\n/** Outcome of one dreaming sweep: counts before and after, and the note written. */\nexport interface DreamingResult {\n status: \"ok\" | \"skipped\" | \"error\";\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n diaryEntryHash: string | undefined;\n /**\n * Deduplicated facts past the per-sweep cap that were not clustered. Set on `\"ok\"`, 0 on\n * `\"skipped\"`, and absent on `\"error\"`, where the sweep cannot say how many it left out.\n */\n factsLeftOut?: number;\n}\n\n/** Run one dreaming sweep (dedupe, cluster, write a consolidated note), serialised per `cwd`. */\nexport function runDreamingSweep(options: DreamingOptions): Promise<DreamingResult> {\n return withCwdMutex(`dream:${options.cwd}`, () => runInner(options));\n}\n\nasync function runInner(options: DreamingOptions): Promise<DreamingResult> {\n const now = options.now ?? Date.now;\n const timestampMs = now();\n try {\n const root = options.memoryRoot ?? resolveMemoryRoot(options.cwd);\n const facts = await readFactsFromMarkdown(\n options.cwd,\n options.memoryRoot ? { directory: options.memoryRoot } : undefined,\n );\n if (facts.length === 0) {\n return emptyResult(\"skipped\");\n }\n const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);\n const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);\n const notesWritten = await writeConsolidatedNotes(root, rem.clusters, timestampMs);\n const result: DreamingResult = {\n status: \"ok\",\n factsBefore: facts.length,\n factsAfter: dedup.kept.length,\n duplicatesRemoved: dedup.duplicatesRemoved,\n clustersCreated: rem.clusters.length,\n notesWritten,\n diaryEntryHash: undefined,\n factsLeftOut: rem.factsLeftOut,\n };\n await appendDiaryEntry(root, {\n timestampMs,\n factsBefore: result.factsBefore,\n factsAfter: result.factsAfter,\n duplicatesRemoved: result.duplicatesRemoved,\n clustersCreated: result.clustersCreated,\n notesWritten: result.notesWritten,\n });\n return result;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] dreaming sweep failed: ${message}\\n`);\n return emptyResult(\"error\");\n }\n}\n\nasync function writeConsolidatedNotes(\n root: MemoryRoot,\n clusters: ReadonlyArray<{ representativeText: string; members: ReadonlyArray<{ text: string }> }>,\n timestampMs: number,\n): Promise<number> {\n if (clusters.length === 0) return 0;\n const notesDir = join(root, \"notes\");\n await mkdir(notesDir, { recursive: true });\n const isoSlug = new Date(timestampMs).toISOString().replace(/[^\\dT]/g, \"-\");\n const file = join(notesDir, `dreamed-${isoSlug}.md`);\n const body = deepPhase(clusters, timestampMs);\n await replaceFileAtomic(file, body);\n return 1;\n}\n\nfunction emptyResult(status: \"skipped\" | \"error\"): DreamingResult {\n const result: DreamingResult = {\n status,\n factsBefore: 0,\n factsAfter: 0,\n duplicatesRemoved: 0,\n clustersCreated: 0,\n notesWritten: 0,\n diaryEntryHash: undefined,\n };\n // An empty store left nothing out; a failed sweep cannot say, so it reports no count.\n return status === \"skipped\" ? { ...result, factsLeftOut: 0 } : result;\n}\n","import { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { defaultIndexPath, openMemoryDb } from \"./index-db.js\";\nimport { LanceIndex, lanceStoragePath } from \"./lance-index.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"./storage/memory-root.js\";\n\n/**\n * Migrate Memory.index from SQLite to LanceDB (ADR D44).\n *\n * EC-3 MUST FIX: validation uses NFC unicode normalization on both sides.\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel (#463).\n */\n\nexport interface MigrateOptions {\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to migrate, when the agent that wrote it\n * set `memory.directory`. Defaults to `<cwd>/.theokit/memory` (#463).\n */\n directory?: string;\n dryRun?: boolean;\n batchSize?: number;\n /** Inject for tests; defaults to console.log. */\n logger?: (msg: string) => void;\n}\n\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n /** Set when validation succeeded (or dryRun); false on validation failure. */\n validated: boolean;\n /** Per-fact compare results (size = sample count, up to 10). */\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n /** Lance storage location (final, after migration). */\n lancePath: string;\n /** Was the migration committed (false for dry-run). */\n committed: boolean;\n}\n\n/**\n * One row of the SQLite memory index, as the Lance migration reads it: the chunk plus the tenant\n * columns the target table needs. Shared with `@theokit/sdk-memory`, which migrates the same table.\n */\nexport interface SqliteFactRow {\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n namespace?: string | null;\n scope?: string | null;\n user_id?: string | null;\n}\n\n/**\n * Read all facts from the SQLite memory index. Returns empty array if the\n * SQLite db file does not exist (workspace never used Memory).\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel, so it carries no visibility\n * tag — naming that tag in this block would delete the function below it (#463).\n */\nexport async function readAllSqliteFacts(root: MemoryRoot): Promise<SqliteFactRow[]> {\n const dbPath = defaultIndexPath(root);\n if (!existsSync(dbPath)) return [];\n const db = await openMemoryDb({ filePath: dbPath });\n try {\n // SQLite schema: chunks table holds the facts. Schema may vary; we\n // probe column existence and fall back to safe defaults.\n const stmt = db.prepare(\"SELECT id, path, source, start_line, end_line, text FROM chunks\");\n const rows = stmt.all() as Array<{\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n }>;\n return rows.map((r) => ({\n ...r,\n namespace: \"default\",\n scope: \"agent\",\n user_id: \"default\",\n }));\n } finally {\n db.close();\n }\n}\n\n/**\n * Compare two strings via NFC normalization (EC-3 MUST FIX). Required\n * because SQLite/Lance native bindings can normalize unicode differently\n * (NFC vs NFD), producing false negatives on facts with accents/emojis.\n *\n * @internal\n */\nfunction nfcEqual(a: string, b: string): boolean {\n return a.normalize(\"NFC\") === b.normalize(\"NFC\");\n}\n\n/**\n * Refuse a `batchSize` the loop below cannot make progress with, before anything is migrated.\n *\n * The loop is `for (let i = 0; i < facts.length; i += batchSize)`, so the three ways this goes wrong\n * are all silent and all different:\n *\n * - 0 or negative: `i` never advances past the guard. The migration SPINS FOREVER, calling\n * `addFacts([])` and writing a \"Migrated x/y\" line every iteration — a hang with unbounded output,\n * which is the worst shape a failure can take because it looks like work.\n * - NaN (`Number(\"abc\")`): `i += NaN` makes the guard false on the first check, zero facts move, and\n * the caller is told \"Validation FAILED. SQLite preserved.\" A typo in an argument is reported as a\n * migration failure.\n * - a fraction: `slice` truncates and the loop still terminates, but the batch boundaries stop\n * matching the number the caller asked for.\n *\n * Validated HERE rather than only in the CLI that motivated the finding, because the CLI is a wrapper\n * over this function and a programmatic caller reaches it with no wrapper at all.\n *\n * @internal\n */\nfunction assertUsableBatchSize(batchSize: number | undefined): void {\n if (batchSize === undefined) return;\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new ConfigurationError(\n `migrateSqliteToLance: batchSize must be a whole number of at least 1; received ${String(batchSize)}.`,\n { code: \"invalid_batch_size\" },\n );\n }\n}\n\n/**\n * Run the migration. Writes Lance to `<cwd>/.theokit/memory/lance-new/`\n * first, validates round-trip, then renames to `lance/` on success.\n * SQLite db is preserved (CLI prompts user to delete).\n *\n * @internal\n */\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: migration is a single transaction (read → write → validate → commit-or-rollback); splitting harms atomicity reasoning.\nexport async function migrateSqliteToLance(opts: MigrateOptions): Promise<MigrateResult> {\n assertUsableBatchSize(opts.batchSize);\n const cwd = opts.cwd;\n // One resolution, reused by every path this migration touches (#463).\n const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });\n const finalPath = lanceStoragePath(memoryRoot);\n const newPath = join(memoryRoot, \"lance-new\");\n // T1.4 (ADR D68): wrap logger so any fact text containing secrets is\n // masked before reaching the destination (console or user-supplied sink).\n // Caller-supplied loggers cannot bypass — by design (D70).\n const rawLog = opts.logger ?? ((m: string) => console.log(m));\n const log = (m: string) => rawLog(redactSecrets(m));\n\n // EC: destination exists → typed error.\n if (existsSync(finalPath)) {\n throw new ConfigurationError(\n `Destination already exists: ${finalPath}. Remove it manually (\\`rm -rf ${finalPath}\\`) and re-run.`,\n { code: \"migration_destination_exists\" },\n );\n }\n if (existsSync(newPath)) {\n // Leftover from a previous failed/interrupted migration. Safe to delete.\n log(`Removing stale ${newPath} from a previous run...`);\n rmSync(newPath, { recursive: true, force: true });\n }\n\n log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);\n const sqliteFacts = await readAllSqliteFacts(memoryRoot);\n log(`SQLite has ${sqliteFacts.length} facts.`);\n if (sqliteFacts.length === 0) {\n return {\n countSqlite: 0,\n countLance: 0,\n validated: true,\n sampleComparisons: [],\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Reuse the embedding runtime configured in the workspace? For v1.2 we\n // require the caller to pass embedding explicitly via env. The migration\n // path is documented as: \"set OPENAI_API_KEY (or similar) before running.\"\n // Here we ship a placeholder embedder that uses a deterministic\n // content-hash — sufficient for migration validation; consumers should\n // re-embed on first real query after migration if needed.\n const placeholderEmbedding = {\n id: \"migration-placeholder\",\n model: \"deterministic-hash\",\n dimension: 8,\n embed: async (texts: ReadonlyArray<string>) => {\n // Simple deterministic hash → 8-dim vector (migration validation only).\n return texts.map((t) => {\n const arr = new Array(8).fill(0);\n for (let i = 0; i < t.length; i += 1) {\n arr[i % 8] += t.charCodeAt(i);\n }\n return arr.map((x) => x / 1000);\n });\n },\n stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 }),\n };\n\n mkdirSync(newPath, { recursive: true });\n log(`Writing Lance index to ${newPath} ...`);\n\n const lance = await LanceIndex.open({\n cwd,\n embedding: placeholderEmbedding,\n storagePath: newPath,\n });\n\n const batchSize = opts.batchSize ?? 100;\n for (let i = 0; i < sqliteFacts.length; i += batchSize) {\n const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({\n id: f.id,\n text: f.text,\n source: f.source,\n namespace: f.namespace ?? \"default\",\n scope: f.scope ?? \"agent\",\n user_id: f.user_id ?? \"default\",\n timestamp: 0,\n }));\n await lance.addFacts(batch);\n log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);\n }\n\n // Validation: count + sample compare (10 random) with NFC normalization.\n const lanceCount = await lance.countFacts(\"default\");\n log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);\n\n const sampleSize = Math.min(10, sqliteFacts.length);\n const sampleComparisons: { id: string; match: boolean }[] = [];\n for (let i = 0; i < sampleSize; i += 1) {\n const sqliteFact = sqliteFacts[Math.floor((i * sqliteFacts.length) / sampleSize)];\n if (sqliteFact === undefined) continue;\n // Search Lance for this fact's text — best-effort round-trip.\n const hits = await lance.search(sqliteFact.text, {\n namespace: sqliteFact.namespace ?? \"default\",\n limit: 1,\n });\n // EC-3: compare with NFC normalization.\n const hit = hits[0];\n const match = hit !== undefined && nfcEqual(hit.text, sqliteFact.text);\n sampleComparisons.push({ id: sqliteFact.id, match });\n }\n\n const allMatch = sampleComparisons.every((c) => c.match);\n const countMatch = lanceCount === sqliteFacts.length;\n const validated = allMatch && countMatch;\n\n await lance.close();\n\n if (opts.dryRun === true) {\n log(\"Dry-run mode — discarding Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n if (!validated) {\n log(\"Validation FAILED — leaving SQLite intact, removing Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: false,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Atomic commit via rename.\n renameSync(newPath, finalPath);\n log(`Migration committed to ${finalPath}.`);\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: true,\n sampleComparisons,\n lancePath: finalPath,\n committed: true,\n };\n}\n"]}
|
|
@@ -48,7 +48,7 @@ function persistTurnToTranscript(store, loc, sessionId, turn, onCompact) {
|
|
|
48
48
|
const count = (recordCounts.get(key) ?? 0) + 1;
|
|
49
49
|
recordCounts.set(key, count);
|
|
50
50
|
if (turn.autoCompact !== void 0) {
|
|
51
|
-
const { autoCompactIfNeeded } = await import('./compact-session-
|
|
51
|
+
const { autoCompactIfNeeded } = await import('./compact-session-CHBJOYWP.cjs');
|
|
52
52
|
const fired = await autoCompactIfNeeded({
|
|
53
53
|
store,
|
|
54
54
|
loc,
|
|
@@ -114,5 +114,5 @@ exports.flushSessionWrites = flushSessionWrites;
|
|
|
114
114
|
exports.getSessionMessages = getSessionMessages;
|
|
115
115
|
exports.hydrateSession = hydrateSession;
|
|
116
116
|
exports.persistTurnToTranscript = persistTurnToTranscript;
|
|
117
|
-
//# sourceMappingURL=chunk-
|
|
118
|
-
//# sourceMappingURL=chunk-
|
|
117
|
+
//# sourceMappingURL=chunk-FBIDOOJM.cjs.map
|
|
118
|
+
//# sourceMappingURL=chunk-FBIDOOJM.cjs.map
|