Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
summarize over-budget memories before embedding instead of truncating
[._.]/ Adam Eivy8ee45c660f76
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6bb8bdb200..b1f0f5c811 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Long memories are summarized to fit the embedding context instead of truncated — so search sees the whole conversation** — Plain truncation embeds only the first ~5k chars of an over-budget record, so for a long ChatGPT chat (≈1/3 of a typical import exceed the budget) everything after the opening is invisible to semantic search. Now, when a record overflows the embedding model's context, PortOS first asks a larger-context local model (the Brain default provider/model — `gpt-oss:20b` on a typical install) to compress it to an embedding-sized gist and embeds **that**, so the vector represents the entire record. For a ChatGPT-import record it summarizes the **full archived transcript** (via `sourceRef`), not the capped preview — fixing both the embedder overflow and the import's content cap in one pass. Within-budget records embed directly (no extra LLM call); if no summarizer provider is configured or the call fails, it falls back to truncate-and-retry so the record still gets an embedding. (`server/services/memorySummarizer.js`, `server/services/memoryEmbeddings.js`, `server/services/brainMemoryBridge.js`)+- **Train a LoRA for any universe-bible subject — objects and places, not just characters** — LoRA training datasets were hardwired to a universe's `characters`; you couldn't build an adapter for a signature weapon, artifact, or location. Datasets now carry an **`entryKind`** (`characters` / `objects` / `places`) alongside the entry id, so the find-or-create / reassignment key is the full `(universeId, entryKind, entryId)` tuple — the same entry id can own one dataset per kind, and a run can't re-own a dataset that was reassigned to a different kind. The "New dataset" and "Reassign" dialogs gain a **Subject type** select (the picker reads `universe[entryKind]` and resets the entry when either the universe or the kind changes); the generate-batch dialog relabels its variation axes per kind (Expressions/Outfits for characters, Lighting/Settings for objects & places) and the prompt builder renders single-object / single-location training prompts (with kind-specific negative prompts) instead of the character figure layout. The record sanitizer defaults a missing `entryKind` to `characters`, so existing datasets and older clients keep working with no migration. (`server/lib/loraDataset.js`, `server/services/loraDatasets.js`, `server/services/loraDatasetGenerate.js`, `server/services/loraTraining/{index,sidecar}.js`, `server/routes/loraDatasets.js`, `client/src/components/loraTraining/{UniverseCharacterPicker,GenerateBatchDialog,TrainingPanel,CharacterLoraChip}.jsx`, `client/src/pages/{LoraTraining,LoraDatasetDetail}.jsx`, `client/src/services/apiLoraTraining.js`)- **Choose your embedding provider + model in Brain config, and reprocess on demand** — Memory's semantic search (pgvector) was hardwired to LM Studio with a fixed embedding model name, so an install running **Ollama** got silent embedding failures — records imported/captured fine but landed with a NULL embedding (unsearchable), and there was no UI to point embeddings elsewhere. Brain → Config gains an **Embeddings (semantic search)** card: pick the embedding **provider** (any OpenAI-compatible backend — Ollama, LM Studio, …) and **model** (e.g. `nomic-embed-text` on Ollama, 768-dim — matches the `vector(768)` column), with a live reachability/model-present status line and a **Reprocess all embeddings** button that re-embeds every brain record (the existing `bridge-sync?refresh` path, which drains sequentially in the background). The embedding service is now **provider-aware**: the LM-Studio-only model discover/load dance (`/api/v0/models` + `/api/v1/models/load`) is skipped for other backends (which serve `/v1/embeddings` directly and don't implement those endpoints — previously it 404'd every call and never latched), and a non-LM-Studio provider's configured model id is authoritative instead of being guessed from a substring match. (`server/services/memoryEmbeddings.js`, `client/src/components/brain/tabs/ConfigTab.jsx`)diff --git a/PLAN.md b/PLAN.mdindex f64c9bb7e4..8de35e101c 100644--- a/PLAN.md+++ b/PLAN.md@@ -20,6 +20,8 @@ independently.<!-- reference-watch proposals: slug-tagged, picked up by /claim later -->+- [ ] [brain-memory-delete-hard-prune-vector] **Hard-delete the mapped pgvector row when a brain memory is deleted by the user (vs a peer-sync tombstone), instead of soft-archiving it forever.** Surfaced 2026-06-14 while wiring ChatGPT-import embeddings. Deleting a brain memory emits `{type}:deleted` → the bridge's `archiveMappedMemory` does `UPDATE memories SET status='archived'` (`brainMemoryBridge.js:373`). That correctly hides it from search (search filters `status='active'`), but the row + its 768-dim embedding **stay in Postgres forever** — nothing ever hard-prunes bridge-archived rows (`memoryDB.deleteMemory(id, hard=true)` exists but the bridge never calls it). For a 1482-record ChatGPT import that's later cleared, that's ~1482 dead vectors lingering. Fix: distinguish a **real local delete** (user action via `remove()` → genuine tombstone) from a **sync-driven archive** (peer delete, recoverable — must stay soft so resurrection works, see the reactivation path at `brainMemoryBridge.js:~193`). On a real local delete, hard-`DELETE` the mapped memory row + drop its bridge-map entry; keep soft-archive for the sync path. The signal is available: `handleEntityDeleted`/`resyncBrainRecord` know whether they're handling a local `:deleted` event vs a `sync:applied` resync. Add a test asserting a local delete removes the row (not just archives) while a synced delete still soft-archives. Note: the `*.db.test.js` real-Postgres guard applies. Estimated scope: small-medium.+- [ ] [media-jobs-survive-pm2-server-restart] **Isolate long media-job subprocesses (LoRA training, video gen) from pm2's restart SIGINT via spawn-side double-fork.** Surfaced 2026-06-14: a 9B LoRA training run died repeatedly with `SIGINT`/`KeyboardInterrupt` at the exact second of a `pm2 restart portos-server`. Root cause: pm2's `TreeKill.js` does `ps -e -o pid=,ppid=` and walks the **parent→child tree**, SIGINT-ing every descendant on restart/stop — and portos-server restarts routinely (was a hardcoded `max_memory_restart: 2G`, now raised + `PORTOS_SERVER_MAX_MEMORY`-configurable, default 4G). `detached: true` does NOT help (TreeKill keys on ppid, not process group); `treekill: false` on the app does NOT work either (pm2 then fails to reap the old node process → it lingers on :5555 → new instance EADDRINUSE crash-loops — tried and reverted). The correct fix is spawn-side: **double-fork the trainer/video-gen child so it reparents to launchd/init (ppid=1) and leaves pm2's tree**, while still streaming stdout for progress (e.g. an intermediate `setsid` launcher that pipes through a fifo/file the parent tails, or a tiny detached supervisor). Apply to BOTH `server/services/loraTraining/index.js:~501` AND `server/services/videoGen/local.js:~918` (same vulnerability). Validate: note the child pid, `pm2 restart portos-server`, confirm the SAME pid keeps running and the job completes. Until then, the raised memory ceiling minimizes restarts and checkpoint-resume recovers any that slip through. Estimated scope: medium.- [ ] [lora-training-caption-strips-invariant-identity] **Character-LoRA captions must NOT describe invariant identity — warn/strip it, or the trigger token never learns the character.** Surfaced 2026-06-14 training Freydis (dataset `90043893`). The first 4B LoRA (run `d36562a0`) rendered a generic auburn-haired woman from the bare trigger `freydis_of_quaervarr portrait`, but rendered Freydis *correctly* when the full identity description was in the prompt — proving her identity (white hair, circlet, tooth necklace, leather armor) got bound to the caption PHRASES, not the trigger token. Every one of the 25 captions repeated her invariant features. Fix path that worked: rewrite captions to keep only the trigger + what VARIES (pose, framing, weapon, setting, style) and drop invariant identity, so the trigger absorbs it (retrain ~35 min). **Caption source matters:** Freydis's images were `source: upload` with `captionSource: manual` — i.e. **Codex authored the captions externally (from the character canon/lore — hence "Northwind Cairnblade") and they were submitted through PortOS's manual-caption path** (`loraDatasets.js:393`), NOT produced by PortOS's vision auto-captioner. Codex described *the character* (identity-first), which is backwards for trigger-binding. The root fix is the external Codex prompt that authors these captions (it must follow the character-LoRA recipe: describe only what varies); PortOS's role is a safety net (lint/strip) since it can't control external caption authors. Product improvements: (a) PortOS's own auto-captioner (`server/services/loraDatasetCaption.js`) already says "do not mention the character's name" and scopes to pose/clothing/accessories — that path is fine; the canon-generation path is the offender; (b) add a caption-lint/warn in the dataset workbench that flags when the SAME descriptive fragment (hair/eyes/skin/signature items) appears across most captions — that's identity that should move to the trigger; (c) optionally offer a one-click "strip shared identity fragments" that diffs captions and removes the common invariant block (the manual rewrite done for Freydis, generalized); (d) document the character-LoRA caption recipe in the workbench UI ("describe what changes shot-to-shot, not who she is"). Estimated scope: medium.diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex fde167cc3d..56934c3b45 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -184,8 +184,13 @@ export async function syncBrainRecord(brainType, record) {const key = bridgeKey(brainType, record.id);const existingMemoryId = map[key];- // Generate embedding- const embedding = await embeddings.generateMemoryEmbedding(memoryData).catch(() => null);+ // Generate embedding. Pass the source hints (NOT persisted on memoryData —+ // the memory schema has no such columns) so the embedder can summarize the+ // FULL archived transcript for an over-budget chatgpt-import record rather+ // than the already-capped content preview.+ const embedding = await embeddings+ .generateMemoryEmbedding(memoryData, { source: record.source, sourceRef: record.sourceRef })+ .catch(() => null);if (existingMemoryId) {// Update existing memory. Force status:'active' so a record that wasdiff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsindex eadd3c8dab..dff1e7c2b9 100644--- a/server/services/memoryEmbeddings.js+++ b/server/services/memoryEmbeddings.js@@ -355,10 +355,22 @@ export async function generateBatchEmbeddings(texts) {}/**- * Generate embedding for memory content + metadata- * Combines content with type/category/tags for richer semantic representation+ * Generate embedding for memory content + metadata.+ *+ * Combines content with type/category/tags for a richer semantic vector. When+ * the combined text fits the embedding model's context, it's embedded directly+ * (the common case — no extra cost). When it OVERFLOWS the budget, plain+ * truncation would drop everything past the first ~budget chars (for a long+ * ChatGPT chat, most of it), so we first try to summarize the record to a+ * embedding-sized gist via a larger-context local model (memorySummarizer) and+ * embed THAT — the vector then represents the whole record. If summarization is+ * unavailable or fails, we fall back to generateEmbedding's truncate+retry so+ * the record still gets some embedding.*/-export async function generateMemoryEmbedding(memory) {+export async function generateMemoryEmbedding(memory, sourceHints = {}) {+ await initConfig();+ const config = getConfig();+const parts = [`Type: ${memory.type}`,`Category: ${memory.category || 'general'}`,@@ -366,8 +378,32 @@ export async function generateMemoryEmbedding(memory) {memory.summary || '',memory.content].filter(Boolean);-const text = parts.join('\n');++ // Within budget → embed as-is (no summarization call).+ if (text.length <= embeddingCharBudget(config)) {+ return generateEmbedding(text);+ }++ // Over budget → summarize to fit (lazy import avoids a startup cycle:+ // memorySummarizer imports chatgptImport, which need not load at boot).+ // `sourceHints` ({ source, sourceRef }) lets the summarizer pull the FULL+ // archived transcript for an import record rather than the capped preview;+ // it's passed separately because the memory payload has no such columns.+ const { summarizeForEmbedding } = await import('./memorySummarizer.js');+ const summary = await summarizeForEmbedding({ ...memory, ...sourceHints }, text).catch((err) => {+ console.warn(`⚠️ Embedding summarization errored: ${err.message}`);+ return null;+ });+ if (summary) {+ // Keep the metadata header so summary vectors share the type/category/tags+ // signal with directly-embedded ones.+ const header = parts.slice(0, parts.length - 1).join('\n'); // everything except raw content+ console.log(`🧠 Summarized over-budget memory before embedding (${text.length}→${summary.length} chars)`);+ return generateEmbedding(`${header}\n${summary}`);+ }++ // Summarizer unavailable/failed — truncate+retry fallback.return generateEmbedding(text);}diff --git a/server/services/memoryEmbeddings.test.js b/server/services/memoryEmbeddings.test.jsindex 6babeeaf6b..08e9239c0e 100644--- a/server/services/memoryEmbeddings.test.js+++ b/server/services/memoryEmbeddings.test.js@@ -3,9 +3,12 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Mocks for the config sources memoryEmbeddings reads in initConfig().const getCosConfig = vi.fn();const getProviderById = vi.fn();+const summarizeForEmbedding = vi.fn();vi.mock('./cos.js', () => ({ getConfig: getCosConfig }));vi.mock('./providers.js', () => ({ getProviderById }));+// generateMemoryEmbedding dynamically imports this for over-budget records.+vi.mock('./memorySummarizer.js', () => ({ summarizeForEmbedding }));// memoryBackend pulls in the DB; stub it to just the default config export.vi.mock('./memoryBackend.js', () => ({DEFAULT_MEMORY_CONFIG: {@@ -215,3 +218,58 @@ describe('memoryEmbeddings — context-budget truncation + overflow retry', () =expect(embedCalls().length).toBe(3);});});++describe('generateMemoryEmbedding — summarize over-budget records', () => {+ beforeEach(() => {+ getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'nomic-embed-text' });+ getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });+ });++ const embedOk = () => {+ const body = JSON.stringify({ data: [{ index: 0, embedding: [0.1, 0.2, 0.3] }] });+ return { ok: true, json: async () => JSON.parse(body), text: async () => body };+ };+ const notLmStudio = () => Promise.resolve({ ok: false, status: 404, text: async () => '', json: async () => ({}) });+ const wireFetch = () => {+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((url) => {+ if (String(url).includes('/api/v0/models')) return notLmStudio();+ return Promise.resolve(embedOk());+ });+ };+ const embedBody = () => JSON.parse(fetchSpy.mock.calls.find(c => String(c[0]).includes('/embeddings'))[1].body);++ it('does NOT summarize a within-budget memory (embeds content directly)', async () => {+ wireFetch();+ await embeddings.generateMemoryEmbedding({ type: 'observation', content: 'a short note' });+ expect(summarizeForEmbedding).not.toHaveBeenCalled();+ expect(embedBody().input).toContain('a short note');+ });++ it('summarizes an over-budget memory and embeds the summary, not the raw content', async () => {+ wireFetch();+ summarizeForEmbedding.mockResolvedValue('TIGHT SUMMARY of the whole thing');+ const huge = 'y'.repeat(40000); // well over the 5222-char budget++ await embeddings.generateMemoryEmbedding({ type: 'observation', category: 'personal', content: huge });++ expect(summarizeForEmbedding).toHaveBeenCalledTimes(1);+ const input = embedBody().input;+ expect(input).toContain('TIGHT SUMMARY of the whole thing');+ expect(input).not.toContain('yyyyyyyyyy'); // raw content was replaced+ // Metadata header is retained alongside the summary.+ expect(input).toContain('Type: observation');+ });++ it('falls back to truncated content when summarization is unavailable', async () => {+ wireFetch();+ summarizeForEmbedding.mockResolvedValue(null); // summarizer down / no provider+ const huge = 'z'.repeat(40000);++ const emb = await embeddings.generateMemoryEmbedding({ type: 'observation', content: huge });++ expect(emb).toEqual([0.1, 0.2, 0.3]);+ // Embedded the (truncated) raw content, not a summary.+ expect(embedBody().input).toContain('zzzz');+ expect(embedBody().input.length).toBeLessThan(40000);+ });+});diff --git a/server/services/memorySummarizer.js b/server/services/memorySummarizer.jsnew file mode 100644index 0000000000..7646193d91--- /dev/null+++ b/server/services/memorySummarizer.js@@ -0,0 +1,100 @@+/**+ * Memory Summarizer+ *+ * Compresses an over-long memory into a short, embedding-sized summary so the+ * resulting vector represents the WHOLE record rather than just its first N+ * chars (plain truncation drops everything past the embedding model's context+ * window — for a 2048-token embedder that's ~1/3 of imported ChatGPT chats).+ *+ * Used only when a record exceeds the embedding budget (see memoryEmbeddings.js);+ * short records embed directly with no LLM call. For a ChatGPT-import record we+ * summarize the FULL archived transcript (via `sourceRef`), not the truncated+ * memory preview, so the embedding captures the entire conversation.+ *+ * Self-contained provider plumbing: resolves the Brain default provider/model+ * (gpt-oss:20b on a typical install) and runs one chat completion. Any failure+ * returns null so the caller falls back to truncation — summarization is a+ * quality boost, never a hard dependency of embedding.+ */++import { getProviderById } from './providers.js';+import { loadMeta } from './brainStorage.js';+import { readArchivedConversation } from './chatgptImport.js';+import { runPromptThroughProvider } from '../lib/promptRunner.js';++// Preferred summarizer model when the Brain default doesn't resolve. gpt-oss:20b+// is the typical Brain default and has ample context for a full transcript.+const PREFERRED_MODEL = 'gpt-oss:20b';++// Cap how much source text we hand the summarizer — large-context local models+// still slow down (and can wander) on enormous inputs. 60k chars (~15k tokens)+// comfortably covers a full ChatGPT conversation while bounding latency.+const MAX_SUMMARY_INPUT_CHARS = 60000;++const SUMMARY_SYSTEM_PROMPT =+ 'You compress a conversation or note into a dense, factual summary for semantic search. '+ + 'Capture every distinct topic, question, decision, entity, and conclusion. '+ + 'Prefer keywords and concrete nouns over prose. No preamble, no headings, no markdown — '+ + 'just the summary text. Aim for under 250 words.';++const clamp = (s, n) => (s.length > n ? s.slice(0, n) : s);++/**+ * Resolve the provider+model to summarize with. Prefers the Brain default+ * provider; falls back to the `ollama` provider so a fresh install still works.+ * Returns { provider, model } or null when no usable provider is configured.+ */+async function resolveSummarizer() {+ const meta = await loadMeta().catch(() => null);+ const providerId = meta?.defaultProvider || 'ollama';+ const provider = await getProviderById(providerId).catch(() => null)+ || await getProviderById('ollama').catch(() => null);+ if (!provider) return null;+ const model = meta?.defaultModel || provider.defaultModel || PREFERRED_MODEL;+ return { provider, model };+}++/**+ * Pull the richest available source text for a memory:+ * - a ChatGPT-import record → the FULL archived transcript (sourceRef), so we+ * summarize the whole conversation, not the import's truncated preview;+ * - anything else → the memory's own combined text (passed in as `fallbackText`).+ */+async function resolveSourceText(memory, fallbackText) {+ if (memory?.source === 'chatgpt-import' && memory.sourceRef) {+ const archived = await readArchivedConversation(memory.sourceRef).catch(() => null);+ if (archived?.transcript?.trim()) return archived.transcript;+ }+ return fallbackText;+}++/**+ * Produce an embedding-sized summary of `memory`, or null on any failure (the+ * caller then falls back to truncation). `fallbackText` is the combined+ * type/category/tags/summary/content string the embedder would otherwise embed.+ */+export async function summarizeForEmbedding(memory, fallbackText) {+ const summarizer = await resolveSummarizer();+ if (!summarizer) return null;++ const sourceText = await resolveSourceText(memory, fallbackText);+ if (!sourceText?.trim()) return null;++ const prompt = `${SUMMARY_SYSTEM_PROMPT}\n\n--- CONTENT ---\n${clamp(sourceText, MAX_SUMMARY_INPUT_CHARS)}`;++ const result = await runPromptThroughProvider({+ provider: summarizer.provider,+ model: summarizer.model,+ prompt,+ source: 'memory-embedding-summary'+ }).catch((err) => {+ console.warn(`⚠️ Embedding summarization failed (${summarizer.model}): ${err.message}`);+ return null;+ });++ const text = result?.text?.trim();+ if (!text) return null;+ return text;+}++export const __test = { resolveSummarizer, resolveSourceText, SUMMARY_SYSTEM_PROMPT };diff --git a/server/services/memorySummarizer.test.js b/server/services/memorySummarizer.test.jsnew file mode 100644index 0000000000..b79bc41dab--- /dev/null+++ b/server/services/memorySummarizer.test.js@@ -0,0 +1,95 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const getProviderById = vi.fn();+const loadMeta = vi.fn();+const readArchivedConversation = vi.fn();+const runPromptThroughProvider = vi.fn();++vi.mock('./providers.js', () => ({ getProviderById }));+vi.mock('./brainStorage.js', () => ({ loadMeta }));+vi.mock('./chatgptImport.js', () => ({ readArchivedConversation }));+vi.mock('../lib/promptRunner.js', () => ({ runPromptThroughProvider }));++let summarizer;++beforeEach(async () => {+ vi.resetModules();+ vi.clearAllMocks();+ summarizer = await import('./memorySummarizer.js');+});++describe('memorySummarizer — summarizeForEmbedding', () => {+ it('summarizes the FULL archived transcript for a chatgpt-import record (not the preview)', async () => {+ loadMeta.mockResolvedValue({ defaultProvider: 'ollama', defaultModel: 'gpt-oss:20b' });+ getProviderById.mockResolvedValue({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' });+ readArchivedConversation.mockResolvedValue({ transcript: 'FULL TRANSCRIPT with every turn included' });+ runPromptThroughProvider.mockResolvedValue({ text: ' a dense summary ' });++ const out = await summarizer.summarizeForEmbedding(+ { source: 'chatgpt-import', sourceRef: 'abc.json' },+ 'the short truncated preview'+ );++ expect(readArchivedConversation).toHaveBeenCalledWith('abc.json');+ // The prompt fed the FULL transcript, not the fallback preview.+ const prompt = runPromptThroughProvider.mock.calls[0][0].prompt;+ expect(prompt).toContain('FULL TRANSCRIPT with every turn included');+ expect(prompt).not.toContain('the short truncated preview');+ // Uses the Brain default model.+ expect(runPromptThroughProvider.mock.calls[0][0].model).toBe('gpt-oss:20b');+ expect(out).toBe('a dense summary'); // trimmed+ });++ it('uses the fallback text for a non-import record (no archive lookup)', async () => {+ loadMeta.mockResolvedValue({ defaultProvider: 'ollama', defaultModel: 'gpt-oss:20b' });+ getProviderById.mockResolvedValue({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' });+ runPromptThroughProvider.mockResolvedValue({ text: 'summary' });++ await summarizer.summarizeForEmbedding({ type: 'observation' }, 'the combined memory text');++ expect(readArchivedConversation).not.toHaveBeenCalled();+ expect(runPromptThroughProvider.mock.calls[0][0].prompt).toContain('the combined memory text');+ });++ it('falls back to the ollama provider when the Brain default does not resolve', async () => {+ loadMeta.mockResolvedValue({ defaultProvider: 'some-removed-provider', defaultModel: 'x' });+ // First lookup (the brain default) misses; the ollama fallback resolves.+ getProviderById.mockImplementation(async (id) =>+ id === 'ollama' ? { id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1', defaultModel: 'gpt-oss:20b' } : null+ );+ runPromptThroughProvider.mockResolvedValue({ text: 'summary' });++ const out = await summarizer.summarizeForEmbedding({ type: 'observation' }, 'text');++ expect(getProviderById).toHaveBeenCalledWith('ollama');+ expect(out).toBe('summary');+ });++ it('returns null when no provider is configured (caller then truncates)', async () => {+ loadMeta.mockResolvedValue({});+ getProviderById.mockResolvedValue(null);++ const out = await summarizer.summarizeForEmbedding({ type: 'observation' }, 'text');++ expect(out).toBeNull();+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ });++ it('returns null when the provider call throws (caller then truncates)', async () => {+ loadMeta.mockResolvedValue({ defaultProvider: 'ollama', defaultModel: 'gpt-oss:20b' });+ getProviderById.mockResolvedValue({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' });+ runPromptThroughProvider.mockRejectedValue(new Error('model timeout'));++ const out = await summarizer.summarizeForEmbedding({ type: 'observation' }, 'text');+ expect(out).toBeNull();+ });++ it('returns null on an empty model response (not an empty string)', async () => {+ loadMeta.mockResolvedValue({ defaultProvider: 'ollama', defaultModel: 'gpt-oss:20b' });+ getProviderById.mockResolvedValue({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1' });+ runPromptThroughProvider.mockResolvedValue({ text: ' ' });++ const out = await summarizer.summarizeForEmbedding({ type: 'observation' }, 'text');+ expect(out).toBeNull();+ });+});