Skip to content

AI, fully local on your computer.

60.3 KB
Raw Blame
import { describe, it, expect, vi } from 'vitest'
import { join } from 'node:path'
import {
  appendMessage,
  buildChatMessages,
  buildSystemPrompt,
  CHAT_RESPONSE_RESERVE_TOKENS,
  collapseToAlternating,
  COMPACTION_SUMMARY_ACK,
  createConversation,
  deleteLastAssistantMessage,
  effectiveContextWindow,
  EmptyCompletionError,
  exportTranscript,
  fitMessagesToContext,
  generateAssistantMessage,
  getLatestMessage,
  isEmptyCompletionError,
  hasRegenerableAssistantReply,
  listConversations,
  listMessages,
  maybeSetTitleFromFirstMessage,
  messageTokens,
  persistAssistantMessage,
  restoreMessage,
  stripThinkBlocks,
  writeCheckpoint
} from '../../src/main/services/chat'
import { endedEarlyAbortReason } from '../../src/main/services/chat/ended-early'
import { createMockRuntime } from '../../src/main/services/runtime/mock'
import { ChatStreamError } from '../../src/main/services/runtime/llama'
import { getSkill, reconcileSkills } from '../../src/main/services/skills/registry'
import type { Db } from '../../src/main/services/db'
import type { ChatMessage, ModelRuntime, RuntimeChatOptions } from '../../src/main/services/runtime'
import type { Citation, ContextUsage, CoverageInfo, KnowledgePackOutcome } from '../../src/shared/types'
import { openFreshDb, tempRoot } from '../helpers/db-fixtures'
import { WIDE_WINDOW, words } from '../helpers/compaction-fixtures'
import { finishScriptedRuntime, recordingRuntime } from '../helpers/scripted-runtime'

function freshDb(): Db {
  return openFreshDb('chat')
}

function runtime() {
  const r = createMockRuntime({ modelId: 'mock-chat', modelPath: '/m.gguf', contextTokens: 2048 })
  return r
}

describe('effectiveContextWindow (§L0 — budget against the real launched window)', () => {
  it('uses the window the runtime reports over settings.contextTokens', () => {
    const runtime = { contextWindow: () => 8192 }
    expect(effectiveContextWindow(runtime, { contextTokens: 4096 })).toBe(8192)
  })

  it('falls back to settings.contextTokens when the runtime reports no window', () => {
    // A bare runtime without the optional accessor (an old test stub).
    expect(effectiveContextWindow({}, { contextTokens: 4096 })).toBe(4096)
  })

  it('falls back to settings when the reported window is zero/non-positive', () => {
    expect(effectiveContextWindow({ contextWindow: () => 0 }, { contextTokens: 4096 })).toBe(4096)
  })

  it('the no-runtime fallback honours the user context-size override before the legacy setting', () => {
    expect(
      effectiveContextWindow({}, { contextTokens: 4096, contextTokensOverride: 16384 })
    ).toBe(16384)
    // A reported window still wins — the launched --ctx-size is the authority (§L0).
    expect(
      effectiveContextWindow({ contextWindow: () => 8192 }, { contextTokens: 4096, contextTokensOverride: 16384 })
    ).toBe(8192)
  })
})

describe('collapseToAlternating (orphan turns from failed answers)', () => {
  const sys = { role: 'system' as const, content: 's' }
  it('drops stale consecutive user turns, keeping the latest (no HTTP 500 from templates)', () => {
    // A conversation where 3 answers failed (each persisted a user turn, no assistant)
    // then a 4th question — the model must still see strictly alternating roles.
    const out = collapseToAlternating([
      sys,
      { role: 'user', content: 'q1' },
      { role: 'user', content: 'q2' },
      { role: 'user', content: 'q3' },
      { role: 'user', content: 'q4' }
    ])
    expect(out).toEqual([sys, { role: 'user', content: 'q4' }])
  })

  it('preserves a normal alternating history unchanged', () => {
    const msgs = [
      sys,
      { role: 'user' as const, content: 'q1' },
      { role: 'assistant' as const, content: 'a1' },
      { role: 'user' as const, content: 'q2' }
    ]
    expect(collapseToAlternating(msgs)).toEqual(msgs)
  })

  it('buildChatMessages collapses orphan user turns left by failed answers', () => {
    const db = freshDb()
    const conv = createConversation(db, { modelId: 'mock-chat' })
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'first' })
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'second' })
    const built = buildChatMessages(db, conv.id, WIDE_WINDOW)
    expect(built.filter((m) => m.role === 'user')).toEqual([{ role: 'user', content: 'second' }])
  })
})

// `words(n)` (tests/helpers/compaction-fixtures): n whitespace-separated words ≈ n approx-tokens (the
// prose path of approxTokenCount), so message sizes in these tests are predictable.

describe('fitMessagesToContext (history budget vs the model context window)', () => {
  const sys = { role: 'system' as const, content: words(10) }

  it('returns the history unchanged when the whole history already fits', () => {
    const msgs: ChatMessage[] = [
      sys,
      { role: 'user', content: words(5) },
      { role: 'assistant', content: words(5) },
      { role: 'user', content: words(5) }
    ]
    // Huge context → nothing to trim → the history comes back unchanged (no needless churn).
    expect(fitMessagesToContext(msgs, 8192)).toEqual(msgs)
  })

  it('drops the OLDEST turns, keeping the system message + a contiguous recent tail', () => {
    const turns: ChatMessage[] = []
    for (let i = 0; i < 6; i++) {
      turns.push({ role: i % 2 === 0 ? 'user' : 'assistant', content: words(200) })
    }
    const msgs: ChatMessage[] = [sys, ...turns]
    // The shipped answer reserve on top, so the history budget is exactly 900; a small budget forces a trim.
    const fitted = fitMessagesToContext(msgs, 900 + CHAT_RESPONSE_RESERVE_TOKENS)

    expect(fitted.length).toBeLessThan(msgs.length)
    expect(fitted[0]).toBe(sys) // system always kept
    expect(fitted[fitted.length - 1]).toBe(turns[turns.length - 1]) // current turn always kept
    // What survives is a contiguous suffix of the original turns (preserves alternation).
    const keptTurns = fitted.slice(1)
    expect(keptTurns).toEqual(turns.slice(turns.length - keptTurns.length))
  })

  it('keeps the final turn even when it ALONE exceeds the budget (runtime maps the overflow)', () => {
    const old = { role: 'user' as const, content: words(20) }
    const huge = { role: 'user' as const, content: words(5000) }
    const fitted = fitMessagesToContext([sys, old, huge], 1000 + CHAT_RESPONSE_RESERVE_TOKENS)
    // The oversize current question is never dropped; only the older turn is.
    expect(fitted).toEqual([sys, huge])
  })

  it('buildChatMessages trims old history when given a small context window', () => {
    const db = freshDb()
    const conv = createConversation(db, { modelId: 'mock-chat' })
    // A long, alternating conversation that would overflow a small context window.
    for (let i = 0; i < 10; i++) {
      appendMessage(db, { conversationId: conv.id, role: 'user', content: words(300) })
      appendMessage(db, { conversationId: conv.id, role: 'assistant', content: words(300) })
    }
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'FINAL QUESTION' })

    const full = buildChatMessages(db, conv.id, WIDE_WINDOW) // room for the whole history
    const fitted = buildChatMessages(db, conv.id, 2048) // budgeted to the model context

    expect(fitted.length).toBeLessThan(full.length)
    expect(fitted[0].role).toBe('system')
    // The current question is always the last message the model sees.
    expect(fitted[fitted.length - 1]).toEqual({ role: 'user', content: 'FINAL QUESTION' })
  })
})

// CB-1 (chat-docs audit 2026-07-07) — after a trim, the kept tail must be user-first. A contiguous
// suffix preserves ALTERNATION but not first-role parity: an even-length kept run ends `user` and so
// BEGINS `assistant`, which strict templates (Mistral-family) reject with HTTP 500. fitMessagesToContext
// drops leading assistant turns in the trimmed branch only; the no-trim identity path stays byte-identical.
describe('fitMessagesToContext — user-first normalization (CB-1)', () => {
  const sys = { role: 'system' as const, content: words(10) }
  // `tag` counts as one word (≤ ONE_TOKEN_WORD_CHARS) so every turn is exactly `n` approx-tokens,
  // making the trim boundary predictable while keeping each turn uniquely identifiable.
  const tagged = (tag: string, n: number): string => [tag, ...Array(n - 1).fill('word')].join(' ')

  it('drops a leading assistant when an even-length tail would otherwise be assistant-first', () => {
    // 5 turns; each 100 words ≈ 203 tokens, sys ≈ 28. A history budget of 900 keeps u4,a3,u2,a1 (four
    // turns, even) → without the fix the tail is [a1,u2,a3,u4] (assistant-first). The fix drops a1.
    const u0 = { role: 'user' as const, content: tagged('U0', 100) }
    const a1 = { role: 'assistant' as const, content: tagged('A1', 100) }
    const u2 = { role: 'user' as const, content: tagged('U2', 100) }
    const a3 = { role: 'assistant' as const, content: tagged('A3', 100) }
    const u4 = { role: 'user' as const, content: tagged('U4', 100) }
    const fitted = fitMessagesToContext([sys, u0, a1, u2, a3, u4], 900 + CHAT_RESPONSE_RESERVE_TOKENS)

    expect(fitted[0]).toBe(sys)
    expect(fitted[1].role).toBe('user') // user-first after system
    expect(fitted.map((m) => m.content)).not.toContain(a1.content) // the leading assistant is gone
    expect(fitted.at(-1)).toBe(u4) // the mandatory final user turn is kept
    // Only the one leading assistant is dropped — the rest of the recent tail survives.
    expect(fitted.slice(1)).toEqual([u2, a3, u4])
  })

  it('never replays the compaction summary ack without its intro (pair never split)', () => {
    // The synthetic pair leads: intro(user) → ack(assistant) → final(user). A budget that keeps the
    // ack but drops the intro would replay a bare "Understood — I'll continue…" with no summary.
    const intro = { role: 'user' as const, content: tagged('INTRO', 100) }
    const ack = { role: 'assistant' as const, content: COMPACTION_SUMMARY_ACK }
    const q = { role: 'user' as const, content: tagged('QUESTION', 100) }
    // sys 28 + q 203 = 231; +ack(≈26)=257 fits a history budget of 300, +intro(203)=460 does not:
    // the fill keeps the ack, then the CB-1 pop drops it as the leading assistant turn.
    const fitted = fitMessagesToContext([sys, intro, ack, q], 300 + CHAT_RESPONSE_RESERVE_TOKENS)

    expect(fitted).toEqual([sys, q])
  })

  it('a solo oversize final turn is preserved — the length-1 guard never empties the tail', () => {
    // The resting meter's shape: the history ends on the assistant reply.
    const finalA = { role: 'assistant' as const, content: tagged('FINAL', 5000) }
    const fitted = fitMessagesToContext(
      [sys, { role: 'user', content: tagged('Q', 20) }, finalA],
      1000 + CHAT_RESPONSE_RESERVE_TOKENS
    )
    // Only the mandatory final turn fits; it is kept even though it alone exceeds the budget.
    expect(fitted).toEqual([sys, finalA])
  })
})

// CB-6 (chat-docs audit 2026-07-07) — getLatestMessage is a LIMIT-1 twin of listMessages used by
// buildTurnFence to size a turn against just the final message instead of paging the whole history.
// It MUST be byte-identical to listMessages(...).at(-1) or the fence content would silently change.
describe('getLatestMessage — LIMIT-1 twin of listMessages (CB-6)', () => {
  it('returns the tail message, byte-identical to listMessages(...).at(-1)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q1' })
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a1' })
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'final question' })
    expect(getLatestMessage(db, conv.id)).toEqual(listMessages(db, conv.id).at(-1))
    expect(getLatestMessage(db, conv.id)?.content).toBe('final question')
  })

  it('excludes a compaction checkpoint row (the tail is the last real turn, not the summary)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q1' })
    const last = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a1' })
    // A checkpoint is written AFTER the last real turn (higher rowid) — it must not become the tail.
    writeCheckpoint(db, { conversationId: conv.id, summary: 'SUMMARY body', coversThroughRowid: 0 })
    const latest = getLatestMessage(db, conv.id)
    expect(latest?.id).toBe(last.id)
    expect(latest?.content).toBe('a1')
    expect(latest).toEqual(listMessages(db, conv.id).at(-1))
  })

  it('returns null for an empty conversation', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    expect(getLatestMessage(db, conv.id)).toBeNull()
  })

  it('matches on a skill-stamped assistant tail (the skills JOIN column is populated)', () => {
    const db = freshDb()
    // Reconcile the shipped app skills so the stamped id resolves through the real skills table.
    reconcileSkills(db, {
      appSkillsDir: join(__dirname, '../../../../app-skills'),
      userSkillsDir: tempRoot('chat-skills')
    })
    const skill = getSkill(db, 'app:bank-statement')!
    expect(skill.title).toBeTruthy()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'Summarize.' })
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'Done.', skillId: skill.installId })
    const twin = getLatestMessage(db, conv.id)
    expect(twin).toEqual(listMessages(db, conv.id).at(-1))
    expect(twin?.skillId).toBe('app:bank-statement')
    expect(twin?.skillTitle).toBe(skill.title)
  })
})

describe('conversation persistence', () => {
  it('creates a conversation and lists it back', () => {
    const db = freshDb()
    const conv = createConversation(db, { modelId: 'mock-chat' })
    expect(conv.id).toMatch(/[0-9a-f-]{36}/)
    expect(conv.title).toBe('New chat')
    expect(conv.mode).toBe('chat')

    const list = listConversations(db)
    expect(list).toHaveLength(1)
    expect(list[0].id).toBe(conv.id)
    expect(list[0].modelId).toBe('mock-chat')
  })

  it('orders conversations by most recently updated', async () => {
    const db = freshDb()
    const a = createConversation(db, {})
    const b = createConversation(db, {})
    // Touch `a` so it becomes the most recently updated. The 5 ms wall-clock gap IS the
    // semantics (updated_at has ISO-8601 ms resolution; setTimeout never fires early) — a
    // clock-advance, not a sync point (TS-1: justified fixed sleep).
    await new Promise((r) => setTimeout(r, 5))
    appendMessage(db, { conversationId: a.id, role: 'user', content: 'hi' })
    const list = listConversations(db)
    expect(list[0].id).toBe(a.id)
    expect(list[1].id).toBe(b.id)
  })

  it('sets the title from the first user message', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'What is a vector store?' })
    maybeSetTitleFromFirstMessage(db, conv.id, 'What is a vector store?')
    expect(listConversations(db)[0].title).toBe('What is a vector store?')
    // A second message must not overwrite the established title.
    maybeSetTitleFromFirstMessage(db, conv.id, 'second question')
    expect(listConversations(db)[0].title).toBe('What is a vector store?')
  })

  // CODE-17 (full-audit 2026-07-11): the auto-title cut is code-point-safe (the RAG-2
  // truncateSnippet idiom) — a raw `.slice(0, 60)` counts UTF-16 units and can cut inside a
  // surrogate pair, persisting a title that forever renders `�` in the sidebar.
  it('never cuts the auto-title inside a surrogate pair (59 ASCII + emoji)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    const content = 'a'.repeat(59) + '😀😀' // 61 code points; the emoji straddles UTF-16 index 60
    maybeSetTitleFromFirstMessage(db, conv.id, content)
    const title = listConversations(db)[0].title
    // The cut lands on the code-point boundary: 59 ASCII + ONE whole emoji (61 UTF-16 units).
    expect(title).toBe('a'.repeat(59) + '😀')
    // No lone surrogate anywhere (the pre-fix title ended in '\ud83d' → `�`).
    expect(title.isWellFormed?.() ?? !/[\uD800-\uDBFF]$/.test(title)).toBe(true)
  })
})

describe('message ordering', () => {
  it('returns messages in insertion order even at equal timestamps', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    const contents = ['u1', 'a1', 'u2', 'a2', 'u3']
    const roles = ['user', 'assistant', 'user', 'assistant', 'user'] as const
    // Freeze the clock (Date only) so all five rows share one created_at and the rowid tie-break decides.
    vi.useFakeTimers({ toFake: ['Date'] })
    try {
      vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))
      contents.forEach((c, i) => appendMessage(db, { conversationId: conv.id, role: roles[i], content: c }))
    } finally {
      vi.useRealTimers()
    }

    const msgs = listMessages(db, conv.id)
    expect(new Set(msgs.map((m) => m.createdAt)).size).toBe(1) // the title's precondition: equal timestamps
    expect(msgs.map((m) => m.content)).toEqual(contents)
    expect(msgs.map((m) => m.role)).toEqual(roles)
  })

  it('scopes messages to their conversation', () => {
    const db = freshDb()
    const a = createConversation(db, {})
    const b = createConversation(db, {})
    appendMessage(db, { conversationId: a.id, role: 'user', content: 'in-a' })
    appendMessage(db, { conversationId: b.id, role: 'user', content: 'in-b' })
    expect(listMessages(db, a.id).map((m) => m.content)).toEqual(['in-a'])
    expect(listMessages(db, b.id).map((m) => m.content)).toEqual(['in-b'])
  })
})

// ---- Per-message coverage round-trip (full-doc-skills plan Phase 1, D48) -----------
// Phase 1 is pure plumbing: appendMessage persists a `CoverageInfo` to messages.coverage_json
// and rowToMessage parses it back; a message that recorded no coverage (NULL) reads back
// undefined so the renderer falls back to the relevance badge — today's behaviour, unchanged.
describe('message coverage persistence (full-doc-skills D48)', () => {
  it('round-trips a CoverageInfo through appendMessage → listMessages', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    const coverage: CoverageInfo = {
      mode: 'extract',
      chunksCovered: 213,
      chunksTotal: 213,
      unparsedChunks: 2,
      fullyChunked: true
    }
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'analysed', coverage })
    expect(listMessages(db, conv.id).at(-1)?.coverage).toEqual(coverage)
  })

  it('a message that recorded no coverage reads back undefined (NULL → relevance fallback)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'plain answer' })
    expect(listMessages(db, conv.id).at(-1)?.coverage).toBeUndefined()
  })

  it('a malformed/legacy coverage_json degrades to undefined (never breaks the conversation)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    const msg = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a' })
    // Simulate a hand-edited / pre-contract row: non-JSON garbage in the column.
    db.prepare('UPDATE messages SET coverage_json = ? WHERE id = ?').run('{not json', msg.id)
    expect(listMessages(db, conv.id).at(-1)?.coverage).toBeUndefined()
  })
})

// ---- Truncation CAUSE persistence (#498) -------------------------------------------
// The badge names no cause any more; `messages.truncated_cause` carries it per message so the
// tooltip offers the remedy that applies. Additive + nullable: a pre-#498 truncated row has no
// cause stored and must keep reading as 'context', which is exactly what the old badge claimed.
describe('message truncation cause persistence (#498)', () => {
  // #994 adds 'repeat': a whole-document answer the app stopped because it kept repeating itself.
  it.each(['cap', 'repeat'] as const)('round-trips truncatedCause %s through appendMessage → listMessages', (cause) => {
    const db = freshDb()
    const conv = createConversation(db, {})
    const msg = appendMessage(db, {
      conversationId: conv.id,
      role: 'assistant',
      content: 'an answer the app cut',
      truncated: true,
      truncatedCause: cause
    })
    expect(msg.truncatedCause).toBe(cause)
    expect(listMessages(db, conv.id).at(-1)?.truncatedCause).toBe(cause)
  })

  it('a legacy truncated row (truncated=1, truncated_cause NULL) reads back as "context"', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    const msg = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'cut off' })
    // Exactly the shape a pre-#498 app wrote: the flag, no cause.
    db.prepare('UPDATE messages SET truncated = 1, truncated_cause = NULL WHERE id = ?').run(msg.id)
    const read = listMessages(db, conv.id).at(-1)
    expect(read?.truncated).toBe(true)
    expect(read?.truncatedCause).toBe('context')
  })

  it('a complete reply stores no cause even if one is passed (NULL ⇒ undefined)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, {
      conversationId: conv.id,
      role: 'assistant',
      content: 'a complete answer',
      truncatedCause: 'cap'
    })
    const raw = db
      .prepare('SELECT truncated, truncated_cause FROM messages WHERE conversation_id = ?')
      .get(conv.id) as { truncated: number | null; truncated_cause: string | null }
    expect(raw.truncated).toBeNull()
    expect(raw.truncated_cause).toBeNull()
    expect(listMessages(db, conv.id).at(-1)?.truncatedCause).toBeUndefined()
  })
})

// ---- "Ended early" persistence (#600) ------------------------------------------------
// A reply cut by the user stopping or switching the model is marked in its OWN nullable column
// (`messages.ended_early`), never as a truncation: an older app reads an unknown `truncated_cause` as
// "raise the context size", while it ignores this column. A workspace moves between laptops with
// different app versions (success criterion #10), so the read is tolerant and the marker survives
// the regenerate snapshot like every other column.
describe('message "ended early" persistence (#600)', () => {
  it('a reply that ended early reads back with its marker and is not a truncation', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a', endedEarly: 'model' })
    const read = listMessages(db, conv.id).at(-1)
    expect(read?.endedEarly).toBe('model')
    expect(read?.truncated).toBeUndefined()
  })

  it('an unknown stored value (a newer app wrote it) reads as no marker', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    const msg = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a' })
    db.prepare('UPDATE messages SET ended_early = ? WHERE id = ?').run('some-future-cause', msg.id)
    expect(listMessages(db, conv.id).at(-1)?.endedEarly).toBeUndefined()
  })

  // #742: a finish reason reaches the caller only from a stream that ran to its end, so a reply flagged
  // truncated was cut by the ceiling before any abort. A Stop landing after that changed nothing: the row
  // keeps "Reply cut off" alone, never both notes.
  it('a stop that lands on a reply already cut at the ceiling leaves it a truncation, not also "stopped" (#742)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    const stop = new AbortController()
    stop.abort(endedEarlyAbortReason('user'))
    const persist = (content: string, truncated?: boolean) =>
      persistAssistantMessage(db, { conversationId: conv.id, role: 'assistant', content, truncated }, stop.signal)
    const read = (id: string) => listMessages(db, conv.id).find((m) => m.id === id)

    const cut = read(persist('cut at the ceiling', true).id)
    expect(cut?.truncated).toBe(true)
    expect(cut?.endedEarly).toBeUndefined()
    // Control: the same stopped turn marks a partial the ceiling did not cut.
    expect(read(persist('a partial').id)?.endedEarly).toBe('user')
  })
})

describe('system prompt + message assembly', () => {
  it('the plain-chat base prompt answers from the model’s own knowledge and carries no grounding rules', () => {
    const p = buildSystemPrompt()
    expect(p).toContain('You are HilbertRaum')
    // Plain chat answers general questions directly (no offline/no-internet boilerplate every turn).
    expect(p).toContain('from your own knowledge')
    // Document-grounding rules belong to GROUNDED_SYSTEM_PROMPT (rag), NEVER the plain-chat prompt —
    // leaking them made plain chat refuse general questions and push "upload a document" (D:\ testing).
    expect(p).not.toContain('include citations using the provided source labels')
    expect(p).not.toContain('answer only from the context')
    // And no standalone "no internet access" line for the model to parrot on every turn.
    expect(p).not.toContain('You do not have internet access.')
  })

  it('prepends a system message then history in order', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'hello' })
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'hi there' })
    const built = buildChatMessages(db, conv.id, WIDE_WINDOW)
    expect(built[0].role).toBe('system')
    expect(built.slice(1)).toEqual([
      { role: 'user', content: 'hello' },
      { role: 'assistant', content: 'hi there' }
    ])
  })
})

describe('generateAssistantMessage (streaming)', () => {
  // The IPC forwards each onToken 1:1 to the live bubble (chat-stream.ts), and chat-ipc pins one payload: this row is
  // what fails if the service forwards only some tokens while persisting the whole reply.
  it('hands every streamed token to onToken, and the reply is exactly what streamed', async () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'ping' })
    const tokens: string[] = []
    const msg = await generateAssistantMessage(db, runtime(), conv.id, { onToken: (t) => tokens.push(t) })
    expect(tokens.length).toBeGreaterThan(1)
    expect(msg.content).toBe(tokens.join(''))
  })

  it.each([
    ['the runtime reports finish_reason "stop"', undefined],
    ['a user Stop leaves no finish_reason (an aborted stream reports none)', 2]
  ] as const)('a reply that did not end at "length" is NOT flagged truncated — %s', async (_label, abortAtToken) => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'ping' })
    const controller = new AbortController()
    let n = 0
    const msg = await generateAssistantMessage(
      db,
      runtime(),
      conv.id,
      abortAtToken === undefined
        ? {}
        : {
            signal: controller.signal,
            onToken: () => {
              if (++n === abortAtToken) controller.abort()
            }
          }
    )
    expect(msg.content.length).toBeGreaterThan(0) // the reply reached the persist step
    expect(msg.truncated).toBeUndefined()
    expect(listMessages(db, conv.id).at(-1)?.truncated).toBeUndefined()
  })

  it('flags + persists truncated when the runtime reports finish_reason "length"', async () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'tell me everything' })

    // A runtime that streams a partial answer then stops at the context ceiling.
    const cutOffRuntime = finishScriptedRuntime([{ reply: 'a partial answer that runs right into the wall', finish: 'length' }])

    const msg = await generateAssistantMessage(db, cutOffRuntime, conv.id, {})
    expect(msg.truncated).toBe(true)
    // Round-trips through the DB read (messages.truncated → Message.truncated).
    expect(listMessages(db, conv.id).at(-1)?.truncated).toBe(true)
    // #498: plain chat flags ONLY the uncapped case, so its flagged case IS the context window —
    // the badge's tooltip may honestly offer "raise the context size" here.
    expect(msg.truncatedCause).toBe('context')
    expect(listMessages(db, conv.id).at(-1)?.truncatedCause).toBe('context')
  })

  // #290: the runtime's per-request timings reach the caller through `onTimings` — only for a
  // COMPLETED stream, and only when the runtime actually sent them.
  describe('onTimings (#290)', () => {
    const timings = { prompt_n: 12, predicted_n: 615, predicted_ms: 14_640, predicted_per_second: 42 }
    function timedRuntime(finish: (options?: RuntimeChatOptions) => void): ModelRuntime {
      return {
        modelId: 'timed',
        start: async () => {},
        stop: async () => {},
        health: async () => ({ healthy: true, message: 'ok', port: null }),
        contextWindow: () => 2048,
        async *chatStream(_messages: ChatMessage[], options?: RuntimeChatOptions) {
          yield 'a full'
          yield ' answer'
          finish(options)
        }
      }
    }

    it('hands the runtime timings up once for a completed answer', async () => {
      const db = freshDb()
      const conv = createConversation(db, {})
      appendMessage(db, { conversationId: conv.id, role: 'user', content: 'how fast?' })
      const seen: unknown[] = []
      const msg = await generateAssistantMessage(
        db,
        timedRuntime((o) => o?.onFinish?.('stop', timings)),
        conv.id,
        { onTimings: (tm) => seen.push(tm) }
      )
      expect(msg.content).toBe('a full answer')
      expect(seen).toEqual([timings])
      // Nothing about the speed is persisted — the row carries no such column/field.
      expect(Object.keys(listMessages(db, conv.id).at(-1) ?? {})).not.toContain('timings')
    })

    it('never fires when the runtime sent no timings (the mock runtime)', async () => {
      const db = freshDb()
      const conv = createConversation(db, {})
      appendMessage(db, { conversationId: conv.id, role: 'user', content: 'ping' })
      const seen: unknown[] = []
      await generateAssistantMessage(db, runtime(), conv.id, { onTimings: (tm) => seen.push(tm) })
      expect(seen).toEqual([])
    })

    it('refuses timings that arrive on an aborted signal even if the runtime reported them', async () => {
      const db = freshDb()
      const conv = createConversation(db, {})
      appendMessage(db, { conversationId: conv.id, role: 'user', content: 'ping' })
      const controller = new AbortController()
      const seen: unknown[] = []
      const misbehaving = timedRuntime((o) => {
        controller.abort()
        o?.onFinish?.('stop', timings)
      })
      await generateAssistantMessage(db, misbehaving, conv.id, {
        signal: controller.signal,
        onTimings: (tm) => seen.push(tm)
      })
      expect(seen).toEqual([])
    })

    // #737: the guard's other half — the stream itself ended in an AbortError while the turn's signal never aborted.
    // Defense in depth: readChatSSE never reports a finish before an abort. (The truncation flag below the guard has
    // no abort guard on purpose: a finish reason exists only for a stream that ran to its end, #776.)
    it('refuses timings from a stream that then threw an AbortError, even on a signal that never aborted (#737)', async () => {
      const db = freshDb()
      const conv = createConversation(db, {})
      appendMessage(db, { conversationId: conv.id, role: 'user', content: 'ping' })
      const controller = new AbortController()
      const seen: unknown[] = []
      const misbehaving = timedRuntime((o) => {
        o?.onFinish?.('stop', timings)
        throw Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })
      })
      const msg = await generateAssistantMessage(db, misbehaving, conv.id, {
        signal: controller.signal,
        onTimings: (tm) => seen.push(tm)
      })
      expect(controller.signal.aborted).toBe(false) // only the caught AbortError marks the stream as cut short
      expect(msg.content).toBe('a full answer') // the partial persists like any stopped answer
      expect(listMessages(db, conv.id).at(-1)?.content).toBe('a full answer')
      expect(seen).toEqual([])
    })
  })

  // 2026-07-04 user report: a Fast-mode reply that hit the FAST_MAX_TOKENS cap also finishes with
  // 'length', and the badge then claimed "reached the model's context limit" while the meter
  // (truthfully) sat at single-digit percent. A capped run must NOT wear the context-limit badge.
  it('does NOT flag truncated when finish_reason "length" came from a max_tokens cap (Fast mode)', async () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'tell me everything' })

    const cappedRuntime = finishScriptedRuntime([{ reply: 'a quick answer that hits the fast-mode token cap', finish: 'length' }])

    // Fast mode maps to a max_tokens cap inside the runtime — 'length' here means "cap", not window.
    const fast = await generateAssistantMessage(db, cappedRuntime, conv.id, { mode: 'fast' })
    expect(fast.truncated).toBeUndefined()
  })

  // Meter honesty: the assembled prompt (system + fitted history) is reported over the LAUNCHED
  // window so the live meter mirrors what the model actually received — not a renderer guess.
  it('reports the real assembled-prompt usage via onPromptUsage', async () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'ping pong ping pong' })

    // A launched window (2048) that differs from settings.contextTokens (default 4096).
    const rt = recordingRuntime('pong', { contextWindow: 2048 })
    const seen: ContextUsage[] = []
    await generateAssistantMessage(db, rt, conv.id, { onPromptUsage: (u) => seen.push(u) })
    expect(rt.lastMessages[0].role).toBe('system')
    // Exactly the estimate over what the model received (system prompt + fitted history), once.
    expect(seen).toEqual([{ usedTokens: rt.lastMessages.reduce((s, m) => s + messageTokens(m), 0), window: 2048 }])
  })

  it('persists the partial reply when a real-style runtime throws AbortError', async () => {
    // The mock returns cleanly on abort, but a real fetch-backed runtime REJECTS the
    // in-flight request with an AbortError. generateAssistantMessage must treat that as a
    // normal end (persist the partial) rather than letting it propagate (C1 regression).
    // NOTE: no signal is passed and the controller is NOT aborted, so this exercises the
    // `err.name === 'AbortError'` branch of isAbortError specifically — deleting that branch
    // must fail this test.
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'ping' })

    // finishScriptedRuntime yields the reply, then throws an AbortError with no signal involved.
    const throwingRuntime = finishScriptedRuntime([{ reply: 'Partial answer', abort: true }])

    const msg = await generateAssistantMessage(db, throwingRuntime, conv.id, {})
    expect(msg.content).toBe('Partial answer')
    expect(listMessages(db, conv.id).at(-1)?.content).toBe('Partial answer')
  })

  // Only aborts are treated as a normal end; a real failure must reject so the IPC layer
  // emits chat:error (guards against isAbortError being too permissive).
  //
  // F-02 (audit 2026-07-16) consumer semantics, main chat turn: an in-band MID-STREAM error
  // frame (the fixed readChatSSE throws ChatStreamError after some tokens streamed). Pre-fix
  // the stream ended cleanly and the partial persisted as a COMPLETE answer (finishReason null
  // ⇒ truncated=false, no error). Decided semantics (mirrors the CB-5 mid-stream precedent): the
  // typed error PROPAGATES — withChatStream maps it to the friendly `main.chat.streamError`
  // copy — and the partial is never silently persisted as complete.
  it.each([
    ['a plain runtime failure (HTTP 500)', () => new Error('Chat request failed: HTTP 500')],
    ['a mid-stream in-band error frame (F-02)', () => new ChatStreamError('slot error', 'server_error')]
  ] as const)('propagates a NON-abort runtime error unchanged and persists no partial — %s', async (_label, makeError) => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'ping' })
    const err = makeError()
    const failing: ModelRuntime = {
      modelId: 'real-ish',
      start: async () => {},
      stop: async () => {},
      health: async () => ({ healthy: true, message: 'ok', port: 1 }),
      chatStream: async function* () {
        yield 'partial'
        throw err
      }
    }
    // The SAME error object propagates (the typed error reaches the IPC mapping unwrapped)…
    await expect(generateAssistantMessage(db, failing, conv.id, {})).rejects.toBe(err)
    // …and nothing partial was persisted — never a silently "complete" answer in the transcript.
    expect(listMessages(db, conv.id).filter((m) => m.role === 'assistant')).toHaveLength(0)
  })

  // L2 (audit round 4): a stop BEFORE the first token used to persist an empty assistant
  // message — a permanent blank bubble in the transcript. CB-4's abort half: the pre-aborted turn
  // RESOLVES (a plain `await`), so an EmptyCompletionError thrown on abort would fail this row too.
  it('a stop before the first token persists nothing and resolves empty — no EmptyCompletionError on abort (L2, CB-4)', async () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })
    const ac = new AbortController()
    ac.abort() // aborted before any token can stream
    const msg = await generateAssistantMessage(db, runtime(), conv.id, { signal: ac.signal })
    expect(msg.content).toBe('')
    expect(listMessages(db, conv.id)).toHaveLength(1) // only the user turn
  })

  // M1 (audit round 4): after a FAILED generation the conversation ends in a user turn.
  // Regenerate used to delete the most recent assistant message anywhere in history —
  // permanently destroying the answer to a *previous* question.
  it('regenerate never deletes an earlier answer when the last turn is a user message', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'first question' })
    const answer = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'first answer' })
    // A second question whose generation failed → no assistant turn follows it.
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'second question' })

    const deleted = deleteLastAssistantMessage(db, conv.id)
    expect(deleted).toBeNull() // last turn is a user message — nothing to delete
    const history = listMessages(db, conv.id)
    expect(history).toHaveLength(3)
    expect(history.some((m) => m.id === answer.id)).toBe(true) // the earlier answer survives
  })

  // CODE-19 rider (full-audit 2026-07-11, Phase-D observation): a compaction checkpoint row also
  // carries role 'assistant' — when one sits at the conversation tail (generation failed right
  // after the pre-pass persisted it), the regenerate delete must skip it and take the last VISIBLE
  // message, and `hasRegenerableAssistantReply` must agree with what the user sees.
  it('regenerate skips a tail compaction checkpoint — deletes the visible answer, keeps the checkpoint', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'question' })
    const answer = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'the answer' })
    // A checkpoint persisted AFTER the answer (the Phase-D fixture shape).
    writeCheckpoint(db, { conversationId: conv.id, summary: 'summary of older turns', coversThroughRowid: 0 })

    // The checkpoint is invisible bookkeeping: the visible tail is the answer, so regenerate applies…
    expect(hasRegenerableAssistantReply(db, conv.id)).toBe(true)
    const deleted = deleteLastAssistantMessage(db, conv.id)
    // …and deletes the ANSWER, never the checkpoint (pre-fix it took the literal last row).
    expect(deleted?.id).toBe(answer.id)
    const kinds = db
      .prepare('SELECT kind FROM messages WHERE conversation_id = ?')
      .all(conv.id) as Array<{ kind: string | null }>
    expect(kinds.some((k) => k.kind === 'compaction')).toBe(true) // the checkpoint survives
  })

  it('a checkpoint-tail conversation whose visible tail is a USER turn has nothing to regenerate', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'unanswered question' })
    // Generation failed right after the compaction pre-pass persisted the checkpoint (Phase-D shape).
    writeCheckpoint(db, { conversationId: conv.id, summary: 'summary', coversThroughRowid: 0 })

    expect(hasRegenerableAssistantReply(db, conv.id)).toBe(false) // the visible tail is the user turn
    expect(deleteLastAssistantMessage(db, conv.id)).toBeNull() // nothing deleted — checkpoint intact
    const kinds = db
      .prepare('SELECT kind FROM messages WHERE conversation_id = ?')
      .all(conv.id) as Array<{ kind: string | null }>
    expect(kinds.some((k) => k.kind === 'compaction')).toBe(true)
  })

  // F2 (post-merge audit): the regenerate guard restores the prior reply byte-faithfully on a
  // non-abort failure. The delete returns a snapshot; restoreMessage re-inserts it exactly. The
  // recurring bug class is a column left out of `DeletedMessage` and silently stripped on restore
  // (#132/#135 skill offer, #301 P4 pack outcomes, #498 truncation cause, #600 "ended early"), so
  // this compares the whole stored row, not a list of fields.
  it('delete → restore round-trips EVERY column of an assistant reply byte-identically (F2; #132/#135, #301 P4, #498, #600)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'what does it say?' })
    const original = appendMessage(db, {
      conversationId: conv.id,
      role: 'assistant',
      content: 'a grounded answer [S1]',
      tokenCount: 42,
      citations: [{ label: 'S1', sourceTitle: 'contract.pdf', pageNumber: 2 }],
      coverage: { mode: 'extract', fullyChunked: true, chunksCovered: 3, chunksTotal: 3 },
      skillId: 'app:bank-statement',
      autoFired: true,
      truncated: true,
      truncatedCause: 'cap',
      endedEarly: 'model',
      skillOffer: { installId: 'app:bank-statement', title: 'Bank statement helper', source: 'deterministic' },
      packOutcomes: [{ packId: 'uuid-climate', title: 'Klimawandel', status: 'searched', reason: null, found: 5, admitted: 3 }]
    })
    // The stored row minus fts_rowid (a restore re-indexes, so the FTS handle is new by design).
    const rawRow = (): Record<string, unknown> => {
      const row = { ...(db.prepare('SELECT * FROM messages WHERE id = ?').get(original.id) as Record<string, unknown>) }
      delete row.fts_rowid
      return row
    }
    const before = rawRow()
    // Teeth for the NEXT column: every messages column but the two compaction-only ones is populated here, so a column
    // added to the table without being added to this fixture fails this line, and one left out of DeletedMessage
    // reads back NULL below.
    expect(Object.keys(before).filter((k) => before[k] === null).sort()).toEqual(['covers_through_rowid', 'kind'])

    const snapshot = deleteLastAssistantMessage(db, conv.id)
    expect(snapshot).not.toBeNull()
    expect(hasRegenerableAssistantReply(db, conv.id)).toBe(false) // gone — back to the user turn
    expect(listMessages(db, conv.id)).toHaveLength(1)

    restoreMessage(db, snapshot!)
    expect(rawRow()).toEqual(before)
    expect(listMessages(db, conv.id).at(-1)?.id).toBe(original.id) // sorts back to the tail
    expect(hasRegenerableAssistantReply(db, conv.id)).toBe(true) // a regenerable reply again
  })
})

// ---- Answer-depth modes: think-block hygiene + option threading (Phase 20) --------

describe('stripThinkBlocks (wave-1 decision D6 (architecture.md "Chat & streaming"))', () => {
  it('removes closed think blocks and trims the seams', () => {
    expect(stripThinkBlocks('<think>\nstep 1\nstep 2\n</think>\n\nThe answer.')).toBe('The answer.')
    expect(stripThinkBlocks('a <think>x</think> b <think>y</think> c')).toBe('a  b  c')
  })

  it('removes an unclosed trailing block (stream stopped mid-thought)', () => {
    expect(stripThinkBlocks('Partial answer.\n<think>half a thou')).toBe('Partial answer.')
    expect(stripThinkBlocks('<think>only thinking, no answer yet')).toBe('')
  })

  it('returns untouched text as-is (no trimming of normal replies)', () => {
    expect(stripThinkBlocks('  plain reply with spaces  ')).toBe('  plain reply with spaces  ')
    expect(stripThinkBlocks('')).toBe('')
  })
})

describe('answer-depth threading + persistence hygiene (Phase 20)', () => {
  /** A runtime that captures chatStream options and emits reasoning + inline think text. */
  function capturingRuntime(reply: string[]): {
    runtime: ModelRuntime
    seen: { options?: RuntimeChatOptions }
  } {
    const seen: { options?: RuntimeChatOptions } = {}
    const runtime: ModelRuntime = {
      modelId: 'capture',
      start: async () => {},
      stop: async () => {},
      health: async () => ({ healthy: true, message: 'ok', port: 1 }),
      async *chatStream(_m: ChatMessage[], options?: RuntimeChatOptions) {
        seen.options = options
        options?.onReasoning?.('thinking about it…')
        for (const t of reply) yield t
      }
    }
    return { runtime, seen }
  }

  // The narrowing pin (CB-4): a reply that ARRIVED then stripped to empty (all-`<think>`/fence-echo)
  // stays the benign silent-empty — it must NOT throw, distinguishing "produced nothing" from
  // "produced only reasoning" (like the zero-token stop, nothing persists).
  it.each([
    ['an unclosed think block (stream stopped mid-thought)', '<think>aborted before the answer'],
    ['a closed think block', '<think>only thinking, no answer</think>']
  ])('a reply that was ONLY thinking persists nothing and does not throw — receivedAnyToken narrows the CB-4 throw (%s)', async (_label, reply) => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })

    // Resolves (does not reject): tokens arrived, they just stripped away.
    const msg = await generateAssistantMessage(db, capturingRuntime([reply]).runtime, conv.id, {})
    expect(msg.content).toBe('')
    expect(listMessages(db, conv.id)).toHaveLength(1) // only the user turn
  })

  // CB-4 — the `content === ''` early return also fired on a COMPLETED, non-aborted stream that
  // produced no answer token at all (a genuinely empty completion). That looked identical to a
  // silently-answered question after reload. Now such a completion surfaces a friendly, retryable
  // error (EmptyCompletionError → main.chat.emptyCompletion) instead of persisting a blank.
  it('a completed stream that produced ZERO tokens throws EmptyCompletionError (CB-4); only the user turn persists', async () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })

    const { runtime: r } = capturingRuntime([]) // completes cleanly with no delta
    const err = await generateAssistantMessage(db, r, conv.id, {}).catch((e: unknown) => e)
    expect(isEmptyCompletionError(err)).toBe(true)
    expect(err).toBeInstanceOf(EmptyCompletionError)
    expect(listMessages(db, conv.id)).toHaveLength(1) // only the user turn — nothing blank persisted
  })

  it('buildChatMessages scrubs think blocks from replayed assistant turns only', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, {
      conversationId: conv.id,
      role: 'user',
      content: 'literal <think>user text</think> stays'
    })
    appendMessage(db, {
      conversationId: conv.id,
      role: 'assistant',
      content: '<think>legacy persisted reasoning</think>\n\nVisible answer'
    })
    const built = buildChatMessages(db, conv.id, WIDE_WINDOW)
    expect(built[1].content).toBe('literal <think>user text</think> stays')
    expect(built[2].content).toBe('Visible answer')
  })
})

describe('exportTranscript — citation provenance (ZIM wave, #294 review M11)', () => {
  it('renders a document citation exactly as before AND an archive citation with its knowledge-pack locator', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })
    const citations: Citation[] = [
      { label: 'S1', sourceTitle: 'contract.pdf', pageNumber: 12 },
      {
        label: 'S2',
        sourceTitle: 'Treibhausgas',
        section: 'Landwirtschaft',
        sourceKind: 'archive',
        archiveTitle: 'Wikipedia (DE)',
        packId: 'pack-uuid-1',
        articlePath: 'A/Treibhausgas'
      }
    ]
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a [S1][S2]', citations })
    const { markdown } = exportTranscript(db, conv.id)
    expect(markdown).toContain('- [S1] contract.pdf, p. 12')
    expect(markdown).toContain(
      '- [S2] Treibhausgas, Landwirtschaft — knowledge pack: Wikipedia (DE); pack id pack-uuid-1; article A/Treibhausgas'
    )
  })

  it('omits missing archive locator values, never invents them', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })
    const citations: Citation[] = [
      { label: 'S1', sourceTitle: 'Treibhausgas', sourceKind: 'archive', archiveTitle: null, packId: 'pack-uuid-1', articlePath: null }
    ]
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a [S1]', citations })
    const { markdown } = exportTranscript(db, conv.id)
    expect(markdown).toContain('- [S1] Treibhausgas — pack id pack-uuid-1')
    expect(markdown).not.toContain('knowledge pack:')
    expect(markdown).not.toContain('article')
  })

  it('a `\\n` inside articlePath cannot break the line (stripped, single Markdown line)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })
    const citations: Citation[] = [
      {
        label: 'S1',
        sourceTitle: 'Treibhausgas',
        sourceKind: 'archive',
        archiveTitle: 'Wikipedia (DE)\nInjected',
        packId: 'pack-uuid-1',
        articlePath: 'A/Treibhausgas\n- [S99] fake citation'
      }
    ]
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a [S1]', citations })
    const { markdown } = exportTranscript(db, conv.id)
    const lines = markdown.split('\n')
    const line = lines.find((l) => l.startsWith('- [S1]'))
    expect(line).toBeDefined()
    expect(line).not.toContain('\n')
    // The injected "- [S99]" text survives only as INERT text inside the [S1] line — it
    // never starts its OWN line (which is what would make it read as a real citation).
    expect(lines.some((l) => l.startsWith('- [S99]'))).toBe(false)
    expect(line).toBe(
      '- [S1] Treibhausgas — knowledge pack: Wikipedia (DE) Injected; pack id pack-uuid-1; article A/Treibhausgas - [S99] fake citation'
    )
  })

  it('a hand-edited row whose archive locator fields are the wrong TYPE is dropped by the citation validator, never handed untyped to the export or the cards (#294 review M11)', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })
    const msg = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'answer' })
    // A stale / hand-edited payload: S1 is a well-formed archive citation, S2 carries objects
    // where the locator strings belong. `.replace` on a non-string would throw in the export.
    db.prepare('UPDATE messages SET citations_json = ? WHERE id = ?').run(
      JSON.stringify([
        {
          label: 'S1',
          sourceTitle: 'Treibhausgas',
          sourceKind: 'archive',
          archiveTitle: 'Wikipedia (DE)',
          packId: 'pack-uuid-1',
          articlePath: 'A/Treibhausgas'
        },
        {
          label: 'S2',
          sourceTitle: 'Klimawandel',
          sourceKind: 'archive',
          archiveTitle: { toString: 1 },
          packId: 42,
          articlePath: ['A/Klimawandel']
        }
      ]),
      msg.id
    )
    expect(listMessages(db, conv.id).at(-1)?.citations?.map((x) => x.label)).toEqual(['S1'])
    const { markdown } = exportTranscript(db, conv.id)
    expect(markdown.split('\n').filter((l) => l.startsWith('- ['))).toEqual([
      '- [S1] Treibhausgas — knowledge pack: Wikipedia (DE); pack id pack-uuid-1; article A/Treibhausgas'
    ])
    expect(markdown).not.toContain('Klimawandel')
  })
})

// ---- Per-ask knowledge-pack outcomes on the message row (#301 P4, findings M6/M7) ----------
// The honesty column: one recorded outcome per pack the ask selected, so a disabled / missing /
// index-less / failed pack can never be mistaken for "searched and found nothing". It rides the
// same three paths every other answer-metadata column rides — read back, regenerate + restore,
// and the Markdown export — and reads TOLERANTLY, because a hand-edited or newer-build payload
// must never break rendering a conversation.
describe('messages.pack_outcomes_json — per-ask knowledge-pack outcomes (#301 P4, M6/M7)', () => {
  const outcomes: KnowledgePackOutcome[] = [
    { packId: 'uuid-climate', title: 'Klimawandel von Wikipedia', status: 'searched', reason: null, found: 5, admitted: 3 },
    { packId: 'uuid-chem', title: 'Chemie', status: 'skipped', reason: 'not-searchable', found: 0, admitted: 0 },
    { packId: 'uuid-gone', title: null, status: 'skipped', reason: 'removed', found: 0, admitted: 0 }
  ]

  it('round-trips through appendMessage / listMessages / getLatestMessage, and stays NULL without outcomes', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })
    const returned = appendMessage(db, {
      conversationId: conv.id,
      role: 'assistant',
      content: 'an answer',
      packOutcomes: outcomes
    })
    // The returned Message and the re-read row agree — no "present in memory, gone after reload".
    expect(returned.packOutcomes).toEqual(outcomes)
    expect(listMessages(db, conv.id).at(-1)?.packOutcomes).toEqual(outcomes)
    expect(getLatestMessage(db, conv.id)?.packOutcomes).toEqual(outcomes)

    // A pack-less ask writes NULL and reads back undefined — every existing chat stays as it was.
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q2' })
    appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'plain' })
    const plain = getLatestMessage(db, conv.id)!
    expect(plain.packOutcomes).toBeUndefined()
    expect(
      (db.prepare('SELECT pack_outcomes_json AS j FROM messages WHERE id = ?').get(plain.id) as { j: string | null }).j
    ).toBeNull()
    // An EMPTY array is the same as none: nothing to say means no column, not a stored "[]".
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q3' })
    const empty = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'x', packOutcomes: [] })
    expect(empty.packOutcomes).toBeUndefined()
    expect(getLatestMessage(db, conv.id)?.packOutcomes).toBeUndefined()
  })

  it('parses tolerantly: a malformed payload reads as undefined, and unknown or wrong-typed entries are dropped', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    /** What an assistant row whose pack_outcomes_json holds `json` reads back as. */
    const readBack = (json: string | null): KnowledgePackOutcome[] | undefined => {
      appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })
      const msg = appendMessage(db, { conversationId: conv.id, role: 'assistant', content: 'a' })
      db.prepare('UPDATE messages SET pack_outcomes_json = ? WHERE id = ?').run(json, msg.id)
      return getLatestMessage(db, conv.id)?.packOutcomes
    }

    // A malformed, truncated or hand-edited payload must degrade to "no notice", never to a render crash.
    expect(readBack(null)).toBeUndefined()
    expect(readBack('not json')).toBeUndefined()
    expect(readBack('{oops')).toBeUndefined()
    expect(readBack('{"packId":"a"}')).toBeUndefined() // an object, not an array
    expect(readBack('[]')).toBeUndefined()

    const mixed = readBack(
      JSON.stringify([
        { packId: 'ok', title: 'T', status: 'searched', reason: null, found: 2, admitted: 1 },
        // An UNKNOWN reason code (a newer build's, or hand-edited): DROPPED rather than rendered
        // blank — the renderer maps codes to fixed copy and has nothing for this one.
        { packId: 'newer', title: 'T', status: 'skipped', reason: 'quantum-flux', found: 0, admitted: 0 },
        { packId: 'bad-status', title: 'T', status: 'maybe', reason: null, found: 0, admitted: 0 },
        { packId: 42, title: 'T', status: 'searched', reason: null, found: 0, admitted: 0 },
        { title: 'no id', status: 'searched', reason: null, found: 0, admitted: 0 },
        { packId: 'bad-title', title: { x: 1 }, status: 'searched', reason: null, found: 0, admitted: 0 },
        'a string',
        null
      ])
    )
    expect(mixed?.map((o) => o.packId)).toEqual(['ok'])

    // Counts are coerced defensively — a hand-edited negative, fractional, null or string count
    // must never reach the renderer's plural formatting.
    const counts = readBack(
      JSON.stringify([
        { packId: 'a', title: null, status: 'searched', reason: null, found: -3, admitted: 2.7 },
        { packId: 'b', title: null, status: 'searched', reason: null, found: '9', admitted: null }
      ])
    )
    expect(counts).toEqual([
      { packId: 'a', title: null, status: 'searched', reason: null, found: 0, admitted: 2 },
      { packId: 'b', title: null, status: 'searched', reason: null, found: 0, admitted: 0 }
    ])
  })

  it('exports a "Knowledge packs:" block after the sources, and on its own when nothing was cited', () => {
    const db = freshDb()
    const conv = createConversation(db, {})
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q' })
    appendMessage(db, {
      conversationId: conv.id,
      role: 'assistant',
      content: 'a [S1]',
      citations: [{ label: 'S1', sourceTitle: 'contract.pdf', pageNumber: 12 }],
      packOutcomes: outcomes
    })
    const lines = exportTranscript(db, conv.id).markdown.split('\n')
    expect(lines).toContain('Knowledge packs:')
    expect(lines.indexOf('Knowledge packs:')).toBeGreaterThan(lines.indexOf('Sources:'))
    expect(lines).toContain('- Klimawandel von Wikipedia: searched — 3 passage(s)')
    expect(lines).toContain('- Chemie: skipped (not-searchable) — 0 passage(s)')
    // No registration row at all means no title — the id names it, rather than an empty label.
    expect(lines).toContain('- pack uuid-gone: skipped (removed) — 0 passage(s)')

    // The ZERO-CITATION answer — the turn the block matters most on — still carries it.
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q2' })
    appendMessage(db, {
      conversationId: conv.id,
      role: 'assistant',
      content: 'I could not find that in your documents.',
      packOutcomes: [{ packId: 'uuid-chem', title: 'Chemie', status: 'failed', reason: 'timeout', found: 0, admitted: 0 }]
    })
    const second = exportTranscript(db, conv.id).markdown
    expect(second).toContain('- Chemie: failed (timeout) — 0 passage(s)')

    // A newline inside a stored title cannot break the line (the M11 locator rule, applied here).
    appendMessage(db, { conversationId: conv.id, role: 'user', content: 'q3' })
    appendMessage(db, {
      conversationId: conv.id,
      role: 'assistant',
      content: 'a',
      packOutcomes: [
        { packId: 'p', title: 'Wiki\n- [S99] fake citation', status: 'searched', reason: null, found: 1, admitted: 1 }
      ]
    })
    const third = exportTranscript(db, conv.id).markdown.split('\n')
    expect(third).toContain('- Wiki - [S99] fake citation: searched — 1 passage(s)')
    expect(third.some((l) => l.startsWith('- [S99]'))).toBe(false)
  })
})