AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { type IpcMainInvokeEvent } from 'electron'
import { guardedHandleFor } from './guarded-handle'
import { IPC, STREAM } from '../../shared/ipc'
import type { AppContext } from '../services/context'
import {
type ExtractRecordType,
type Message,
type RetrievalScope,
type SkillOffer
} from '../../shared/types'
import {
appendMessage,
effectiveContextWindow,
hasRegenerableAssistantReply,
listMessages,
maybeSetTitleFromFirstMessage,
setMessageSkillOffer
} from '../services/chat'
import { resolveScope } from '../services/collections'
import { buildScopeFilter } from '../services/retrieval-scope'
import {
detectFilenameScope,
documentFitsWholeRead,
generateGroundedAnswer,
generateGroundedDataAnswer,
generateSmallTalkReply,
type GroundedAnswerOptions,
isNoContextAnswer,
modePackOutcomes,
ragSettingsFrom,
WHOLE_READ_SECTION_FRAMING_TOKENS,
wholeDocumentFitBudgetTokens
} from '../services/rag'
import { wholeDocTreeMaterial } from '../services/rag/whole-doc-tree'
import { resolveTurnSkillFromRegistry } from '../services/skills/turn'
import {
BANK_STATEMENT_INSTALL_ID,
getSkillAnalysisHandler,
manifestAnalysisHandler,
type SkillAnalysisHandler
} from '../services/skills/analysis'
import { offerableSkillCandidates } from '../services/skills/suggest'
import { documentsInScope, scopeSectionTotals } from '../services/skills/scope-documents'
import { getSkill, type SkillRecord } from '../services/skills/registry'
import { matchesSkillDocSignals } from '../services/skills/selector'
import { isNeedleShaped, isReportShaped, isSmallTalk, isSmallTalkReply } from '../services/skills/vocabulary'
import type { SkillFenceMode } from '../services/skills/prompt'
import { toSkillToolAudit } from '../services/skills/tool-runs'
import { saveResultTable } from '../services/tables/store'
import { log } from '../services/logging'
import { buildDocumentSegmentReader } from './documentSegments'
import { aggregateExtractions, SCAN_MARKER_TYPE } from '../services/analysis/extract'
import {
classifySkillPointer,
isClassificationTrigger,
type ClassifyCandidate
} from '../services/analysis/classify'
import { makeQueryExpander } from '../services/zim/expand'
import { asksForSummary, isAggregationShaped, isTotalAsk, routeQuestion, type RouteDecision } from '../services/analysis/router'
import { buildListingAnswer } from '../services/analysis/listing-answer'
import { getSettings } from '../services/settings'
import { tMain } from '../services/i18n'
import { resolveRerankProfile, rerankScopeFor, type RerankScope } from '../services/rag/rerank-profile'
import {
resolveRerankerDevicePosture,
snapshotRerankerOccupancy,
type RerankerOccupancySnapshot
} from '../services/rag/device-posture'
import { eligibleDevicesFor, machineKey } from '../services/performance'
import { detectSystem } from '../services/benchmark'
import { defaultThreadCount } from '../services/runtime/sidecar'
import type { AppSettings } from '../../shared/types'
import { workspaceAdmitsWork } from '../services/workspace-vault'
import {
assertChatStreamReady,
resendableQuestion,
withChatStream,
withRegenerateGuard,
type SendCompaction,
type SendToken,
type SendUsage
} from './chat-stream'
import type { Db } from '../services/db'
/**
* This ask's knowledge-pack candidate scope, resolved from `resolveRerankProfile`'s hardware
* profile (`rag/rerank-profile.ts`) — a GPU machine's ask sees `GPU_RERANK_SCOPE` candidates
* whenever the profile resolves `gpu` AND the reranker sidecar's own device posture resolves
* `gpu` too (Wave 6 ruling (a) below). Step 4-5 (ruling (d), B2) re-sourced the reranker
* sidecar's own device POSTURE onto a separate, headroom-gated check (`rerankerDeviceFor`) and
* deliberately left this scope classification alone — so on a small card where the chat model
* leaves too little headroom, the profile can still resolve `gpu` (and therefore this wide
* scope) while the sidecar itself starts `--device none` (CPU posture): the scope this function
* returns and the sidecar's actual posture CAN mismatch. Flagged by the scoped Opus review of
* step 4-5 (finding C1) as unmeasured and undisclosed; **resolved by Wave 6 ruling (a) (step
* 4-6)**: the posture is now resolved through the SAME shared helper the sidecar itself uses
* (`resolveRerankerDevicePosture`, `main/services/rag/device-posture.ts` — Wave 6 ruling (c)) and
* threaded into `rerankScopeFor`, which forces `capped` on the `gpu` profile whenever the
* resolved posture is `cpu` — never a general "posture cpu ⇒ capped" rule (that would also
* capture the always-`cpu`-postured `cpu-hi` branch and kill its `top48` opt-in; see
* `rerankScopeFor`'s own doc comment). The scope this function returns and the sidecar's actual
* posture cannot disagree, because both are resolved through the SAME shared helper with the
* SAME settings AND occupancy snapshot for a given call (Wave 8 ruling (a) below re-sourced the
* posture's chat-model input from `settings.activeModelId` onto the runtime's COMMITTED model —
* a proxy that used to be false for the whole `runtime:use` hash + load window — plus the
* in-flight/pending chat-start state and the translator's occupancy; see
* `rag/device-posture.ts`'s own doc comment for the full history). Step 4-4 added an event-time
* suspend on `settings:update` for `gpuMode`/`gpuAutoDisabled`, and step 4-7 (Wave 7 ruling (a))
* one for `activeModelId` on `models:select` and `runtime:use` (and on `settings:update`, until
* #868 made `gpuMode` the only posture key a renderer patch can carry), so a resident sidecar's
* NEXT `rerank()` would re-resolve promptly — early release, not the guarantee.
* `gpuAutoDisabled` moves only through two seams no suspend covers (`tryGpuAgain`,
* `persistGpuFailure`) — reported, not fixed, for a separate owner ruling; see `channels.json`.
* What actually keeps the two from disagreeing at every MOMENT is the reranker's own use-time
* re-check (`reranker/llama.ts`'s `resolveServer`, Wave 8 ruling (b)(Q)):
* a restart that cannot proceed safely lands on Wave 5 ruling (e)(i)'s `cappedCandidates`
* fallback, never a wide scope on a CPU sidecar and never an ended ask. Absent a reranker
* (`rerankerAvailable: false`), `rerankScopeFor`
* always returns `'capped'` — a MEASURED requirement, not just a defensive default: the `gpu`
* profile's own no-rerank column (the `all` scope through the no-rerank interleave — the
* configuration an ABSENT reranker produces; a rerank-call FAILURE is restricted to the `capped`
* companion instead, since step 4-5 ruling (e)(i)) packed FEWER gold blocks than today's
* `capped`/no-rerank baseline (`allPacked` 26→22, `anyPacked` 42→33 — see
* `docs/known-limitations.md`'s fallback-cost bullet and `docs/rag-design.md` §17). Exported for
* `tests/unit/rerank-profile-wiring.test.ts` and `tests/integration/reranker-callbacks-composition.test.ts`;
* its one production call site is the ask handler below.
*
* `occupancy` (Wave 8 ruling (a)/(b)(G)/NF-1) is a REQUIRED parameter, not optional: the resolved
* posture depends on the committed chat model and its in-flight/pending state and the
* translator's occupancy, never `settings.activeModelId` — an optional parameter defaulting to
* "no occupancy" would silently readmit wide scopes on a small card the instant a caller forgot
* to pass it. The one production call site (below) builds it from `ctx.runtime`/`ctx.translator`
* and the pending-switch counter, the SAME snapshot shape `main/index.ts`'s posture callback
* factory builds (`rag/device-posture.ts`'s `createRerankerCallbacks`), so the sidecar's own
* posture and this per-ask scope cannot disagree for a given call.
*/
export function resolveAskCandidateScope(
settings: AppSettings,
rerankerAvailable: boolean,
manifestsDir: string | null,
occupancy: RerankerOccupancySnapshot
): RerankScope {
const here = machineKey(detectSystem())
const input = {
gpuMode: settings.gpuMode,
gpuAutoDisabled: settings.gpuAutoDisabled,
probeDevices: eligibleDevicesFor(settings, here),
threads: defaultThreadCount(),
rerankerAvailable,
wideScopeOptIn: settings.ragRerankWideScope
}
const posture = resolveRerankerDevicePosture(settings, manifestsDir, occupancy)
return rerankScopeFor(resolveRerankProfile(input), input, posture)
}
/** #733: does the scope hold any section at all, whatever its document's status (retrieval reads the old
* sections of a failed re-index too)? Without one, and without a pack, retrieval can find nothing. */
function sectionsExistInScope(db: Db, scope: RetrievalScope): boolean {
const filter = buildScopeFilter(scope, 'c.document_id')
const where = filter ? ` WHERE ${filter.sql}` : ''
const row = db
.prepare(`SELECT 1 FROM chunks c${where} LIMIT 1`)
.get(...(filter ? filter.params : [])) as unknown as { 1: number } | undefined
return row != null
}
/** Does any in-scope document have precomputed structured-extract data (a `__scan__` marker)?
* Gates the router's coverage-extract branch — without it we cannot honestly claim a complete
* list, so the question falls back to labelled relevance (plan §4.2/§4.4, H7). */
function extractionsExistInScope(db: Db, scope: RetrievalScope): boolean {
const filter = buildScopeFilter(scope, 'document_id')
const where = filter ? ` AND ${filter.sql}` : ''
const row = db
.prepare(
`SELECT 1 FROM extraction_records WHERE record_type = ?${where} LIMIT 1`
)
.get(SCAN_MARKER_TYPE, ...(filter ? filter.params : [])) as unknown as { 1: number } | undefined
return row != null
}
/**
* Exhaustiveness precondition for a tool-skill analysis turn (full-doc-skills §3.2/D45/R4): is EVERY
* indexed, answerable in-scope document `fully_chunked` RIGHT NOW? `documents.fully_chunked` is TEXT;
* non-NULL = fully chunked (NULL = legacy/partly-chunked). Read at turn time (not a cached flag) so a
* doc later edited stale refuses honestly. Mirrors the `documentsInScope` membership/index filter so
* the set checked is exactly the set the handler would analyse. `applies()` already requires a single
* in-scope doc, so this is effectively "is that one doc fully chunked".
*/
function allInScopeDocsFullyChunked(db: Db, scope: RetrievalScope): boolean {
const filter = buildScopeFilter(scope, 'd.id')
const where = filter ? ` AND ${filter.sql}` : ''
const row = db
.prepare(
`SELECT COUNT(*) AS n FROM documents d
WHERE d.status = 'indexed'
AND EXISTS (SELECT 1 FROM chunks c WHERE c.document_id = d.id)
AND d.fully_chunked IS NULL${where}`
)
.get(...(filter ? filter.params : [])) as unknown as { n: number }
return (row?.n ?? 0) === 0
}
/**
* A skill's analysis engine, in precedence order (full-doc-skills Phase 3 / A3, see the turn-skill
* lookup in the handler): the app registry's handler, else the engine its manifest declares
* (`analysis: whole-doc | compare`, honoured for instruction skills only — SEC-1). Undefined means a
* fence-only skill: its fence shapes the prompt, and no engine reads beyond top-k. One spelling for the
* turn's own skill, the #133 engagement filter and the #779 no-context offer drop.
*/
function skillAnalysisHandler(
installId: string,
record: Pick<SkillRecord, 'kind' | 'manifest'> | null
): SkillAnalysisHandler | undefined {
return (
getSkillAnalysisHandler(installId) ?? (record ? manifestAnalysisHandler(record.kind, record.manifest.analysis) : undefined)
)
}
/**
* #643 / #642: the one document a turn bound for top-k retrieval reads WHOLE instead, or null.
*
* Top-k keeps at most `ragTopKFinal` sections and only the best one per PDF page, so even a short
* letter can reach the prompt incomplete. A scope of exactly ONE document whose whole text fits the
* launched window's whole-document budget is read in order instead (`generateGroundedAnswer({
* wholeDocument })` — one grounded turn, every section under its `[Sn]` label), the rule the whole-doc
* skills already follow (A3). `fitBudgetTokens` is that budget for this question + skill.
*
* #642: a summary ask the router sent to `tree-summary` takes the same path when the document is too
* large to read whole but its deep index is ready — `generateGroundedAnswer` reaches the tree map-reduce
* when the read would truncate. Without a ready tree it stays top-k (no surprise chunk map-reduce).
*
* #649: an aggregation ask (a sum, categories) the router sent to `coverage-extract` takes it too when the
* document fits: the listing can only list the values, the whole read can add them up.
*
* Stays top-k: a multi-document scope; a chat with knowledge packs (the whole read never queries
* them); small talk (#963: the short small-talk reply takes most of it before any of this, so what
* reaches here is a filler question such as "Sure?" or a bare "ok", which reads passages); a legacy, partly
* chunked document (its sections are not its whole text, so "covers the whole document" would lie).
*/
function wholeReadDocumentId(
db: Db,
scope: RetrievalScope,
routableDocs: ReadonlyArray<{ id: string }>,
question: string,
fitBudgetTokens: number,
treeSummary: boolean
): string | null {
if (routableDocs.length !== 1) return null
if ((scope.packIds?.length ?? 0) > 0) return null
if (isSmallTalk(question)) return null
if (!allInScopeDocsFullyChunked(db, scope)) return null
const documentId = routableDocs[0]!.id
// Each section also carries its `[Sn] File: …` line, which `retrieveWholeDocument` does not charge.
if (documentFitsWholeRead(db, documentId, fitBudgetTokens, WHOLE_READ_SECTION_FRAMING_TOKENS)) return documentId
// The tree answers only when it is ready AND holds a usable summary (`answerWholeDocFromTree`'s own
// gate); otherwise the whole path would fall to the chunk map-reduce.
if (treeSummary && wholeDocTreeMaterial(db, documentId) != null) return documentId
return null
}
/**
* Count in-scope ANSWERABLE documents with a READY deep-index tree (enables the tree-summary route). #736: a
* document being re-indexed keeps its old tree `ready` until its chunk transaction, and a re-index that failed
* before it keeps it for good, so only `indexed` documents count — the set `documentsInScope` routes over (a
* ready tree implies chunks). Still a scope-wide hint: whether the tree answers is `wholeReadDocumentId`'s call.
*/
function readyTreeCountInScope(db: Db, scope: RetrievalScope): number {
const filter = buildScopeFilter(scope, 'd.id')
const where = filter ? ` AND ${filter.sql}` : ''
const row = db
.prepare(
`SELECT COUNT(*) AS n FROM documents d WHERE d.status = 'indexed' AND d.tree_status = 'ready'${where}`
)
.get(...(filter ? filter.params : [])) as unknown as { n: number }
return row?.n ?? 0
}
// IPC for RAG chat with citations (spec §9.1, §7.8).
//
// `askDocuments(conversationId, question)` is the document-grounded sibling of
// `sendChatMessage`. It REUSES the LOCKED streaming contract — tokens go out on
// `chat:token/done/error:<conversationId>` and the invoke resolves with the final
// assistant Message — so the renderer subscribes exactly as it does for plain chat.
//
// Differences from sendChatMessage: the answer is grounded in retrieved document chunks
// and the assistant turn is persisted WITH citations (→ messages.citations_json). When no
// usable context is retrieved, a fixed "not found in your documents" answer is returned
// without calling the model (grounding rule, spec §7.8). Cancellation reuses the shared
// in-flight registry, so `stopGeneration(conversationId)` cancels a document answer too.
//
// Like sendChatMessage, this does NOT auto-start a runtime — a model must be started on
// the AI Model screen first; with none active the handler throws so the renderer can show
// the "start a model" empty state.
export function registerRagIpc(ctx: AppContext): void {
const ipcHandle = guardedHandleFor(ctx)
// The FAITHFUL content reach a tool-skill analysis handler needs (full-doc-skills §3.2): a
// document's ordered, non-overlapping, newline-preserving parser segments, re-extracted from the
// stored copy — the SAME reader the skills-run IPC injects (`documentSegments.ts`), so the chat
// answer and the run-bar button agree on layout use. The `chunks` table is retrieval windows
// (newlines collapsed, ~80-token overlap), which would give the line-oriented extractors near-zero
// rows. Content stays main-side: only the tool ever sees it.
const readDocumentSegments = buildDocumentSegmentReader(ctx)
ipcHandle(
IPC.askDocuments,
async (
event: IpcMainInvokeEvent,
conversationId: string,
question: string,
skillInstallId?: string | null,
regenerate?: boolean,
pinnedDocumentId?: string | null,
resendMessageId?: string | null
): Promise<Message> => {
// F16 (audit-postmerge-2026-06-29): rag:ask is the document-grounded sibling of
// sendChatMessage and touches ctx.db throughout; gate it FIRST with the same localized chat
// lock copy so a locked call refuses friendly instead of throwing the raw vault-getter string
// deep inside assertChatStreamReady. (Generalized lock test covers this — subsumes T3.)
// AUD-02: `workspaceAdmitsWork`, not a bare `isUnlocked()` — the DB stays OPEN for the
// whole multi-second lock teardown, so a bare check admits an answer that would keep
// driving the embedder/reranker/chat sidecars the teardown just suspended.
if (!workspaceAdmitsWork(ctx.workspace)) throw new Error(tMain('main.chat.locked'))
// Shared guard preamble (M-A2): conv exists, runtime active, no blocking doc task /
// stream already in flight (a yielding deep-index build is paused, not refused).
const { runtime } = await assertChatStreamReady(ctx, conversationId)
// Re-answer the last document turn (S13c "answer without it" undo, symmetric to chat's
// regenerate): drop the previous assistant reply and RE-USE the existing last user turn as the
// question — never append a duplicate user row. The renderer passes `skillInstallId: null` to
// re-run skill-free; with no prior assistant reply there is nothing to regenerate.
const isRegenerate = regenerate === true
// #613 "Send again" (chat's `resendMessageId` twin): the unanswered last question this turn
// answers again, or null (refuses a stale id before anything is written; regenerate wins).
const resend = resendableQuestion(ctx.db, conversationId, isRegenerate, resendMessageId)
let text: string
if (isRegenerate) {
// Only CHECK (read-only) that a prior assistant reply exists, then recover the last USER
// turn as the question. The DESTRUCTIVE delete is deferred into each withChatStream runFn
// below via withRegenerateGuard (F2): committing it here, before the slot was claimed, lost
// the prior answer on a non-abort failure. Finding the last user turn does NOT require
// deleting the assistant reply first — the reverse-find skips the assistant row regardless.
if (!hasRegenerableAssistantReply(ctx.db, conversationId)) {
throw new Error(tMain('main.chat.nothingToRegenerate'))
}
const history = listMessages(ctx.db, conversationId)
text = ([...history].reverse().find((m) => m.role === 'user')?.content ?? '').trim()
if (!text) throw new Error(tMain('main.chat.emptyQuestion'))
} else if (resend != null) {
// The stored question IS the question: nothing appended (no duplicate), nothing deleted.
text = resend.content.trim()
} else {
text = question.trim()
if (!text) throw new Error(tMain('main.chat.emptyQuestion'))
appendMessage(ctx.db, { conversationId, role: 'user', content: text })
maybeSetTitleFromFirstMessage(ctx.db, conversationId, text)
}
// Resolve the one skill for this DOCUMENT turn too (audit A1/§22-A1 — both channels carry the
// skill, else a documents conversation silently gets none). Same resolver as plain chat. The
// question is passed so the resolver can S13b AUTO-FIRE when the turn has no skill set (content —
// scored, not logged; off by default).
const skill = resolveTurnSkillFromRegistry(ctx.db, ctx.skills, conversationId, skillInstallId, text)
// #132: an EXPLICIT per-turn skill id (an offer click / composer pick) that no longer resolves —
// disabled, removed, needs a newer app, or its body no longer parses — REFUSES instead of
// silently degrading to a skill-free re-answer. The resolver's graceful-null is the sticky-DEFAULT
// contract (§10.3); an explicit id is a consent the answer must honor or decline out loud.
// Thrown before any stream/slot/delete work (the F2-deferred regenerate delete never ran), so the
// prior answer is untouched. `null`/`''` (a deliberate skill-free re-run) stays allowed.
if (typeof skillInstallId === 'string' && skillInstallId.length > 0 && skill == null) {
throw new Error(tMain('main.chat.skillUnavailable'))
}
// #963 (follow-ups wave 5 owner call G-1): small talk ("Danke!", "Thanks!", «Merci !», "How are you?") gets one
// short model reply that reads nothing: no scope narrowing, no skill engine, no router, no knowledge-pack search
// and no grounded prompt, so no Sources, coverage meter or skill stamp sit under a thank-you. `isSmallTalkReply`
// is stricter than the `isSmallTalk` opt-outs below: a filler question ("Sure?", «Alles?») and an answer to the
// assistant's own question or offer with no thanks, greeting or praise in it ("ok", "all", «bitte») still read the
// documents, with the conversation. The turn runs
// through the stream, the regenerate guard and the chat slot every answer uses, so Stop, lock, quit, "Send again"
// and regenerate behave as on any turn.
if (isSmallTalkReply(text)) {
return withChatStream(
event,
conversationId,
'Small-talk reply failed',
withRegenerateGuard(ctx.db, conversationId, isRegenerate, (signal, sendToken, _sendReasoning, _sendCompaction, sendUsage) =>
generateSmallTalkReply(ctx.db, runtime, conversationId, text, { signal, onToken: sendToken, onPromptUsage: sendUsage })
),
(signal) => ctx.docTasks?.acquireChatSlot(signal) ?? Promise.resolve(() => {})
)
}
const rawSettings = getSettings(ctx.db)
const settings = ragSettingsFrom(rawSettings)
// Step 4-4: resolved once per ask, from the SAME settings snapshot `settings` above came
// from — reused at the single `externalArm` wiring point below. `ctx.manifestsDir` (Wave 6
// ruling (c)) lets the posture half reach `findManifestById`/`estimateGraphicsNeedMib`.
// Wave 8 ruling (a)/NF-1: `occupancy` is REQUIRED — built by the SAME
// `snapshotRerankerOccupancy` helper `main/index.ts`'s posture-callback factory uses, off
// the SAME `ctx.runtime`/`ctx.translator`, so this per-ask scope and the sidecar's own
// posture cannot disagree for this call. `ctx.pendingModelSwitches` is required (#477): a
// silent always-zero fallback here made a missing wiring indistinguishable from "no model
// switch pending", widening the GPU-contention window the counter exists to close.
// #495 follow-up: `rerankerDemoted` is spread in from `ctx.reranker.gpuDemoted()` — the
// ONE occupancy field `snapshotRerankerOccupancy` itself cannot supply, since the
// sidecar's own posture-callback factory (`createRerankerCallbacks`) builds its occupancy
// before the reranker instance exists. Without it, a demoted session kept asking for
// `GPU_RERANK_SCOPE` here while the sidecar was pinned to `cpu`, and G refused the request.
const candidateScope = resolveAskCandidateScope(
rawSettings,
ctx.reranker != null,
ctx.manifestsDir,
{
...snapshotRerankerOccupancy(ctx.runtime, ctx.pendingModelSwitches, () => ctx.translator ?? null),
rerankerDemoted: ctx.reranker?.gpuDemoted?.() ?? false
}
)
// Resolve the conversation's composite scope (plan §10.1 / D1): the UNION of the
// selected collections (Library / projects), specific docs, and chat attachments.
let scope = resolveScope(ctx.db, conversationId)
// U3 routed-run relay pin (audit ux-6): a Summarize/Categorize button routes its question into
// the transcript pinned to the run's document, so the answer can't scatter across a multi-doc
// scope. The id is UNTRUSTED (renderer-supplied) — re-validate it against the in-scope, indexed
// set (the run-start `documentId` precedent) and narrow ONLY to a real member; an id outside
// scope is ignored (the ordinary scope stands). `hasExplicitDocSelection` marks it a deliberate
// pick so the filename auto-scope below defers to it. NOT a routing-engine change — the same
// handler dispatch runs, only over one document.
if (typeof pinnedDocumentId === 'string' && pinnedDocumentId.length > 0) {
const inScope = documentsInScope(ctx.db, scope, { requireChunks: true })
if (inScope.some((d) => d.id === pinnedDocumentId)) {
scope = { ...scope, collectionIds: null, documentIds: [pinnedDocumentId], hasExplicitDocSelection: true }
}
}
// Filename auto-scope narrows WITHIN the resolved scope (plan §10.1 rule 5): when the
// question names indexed file(s) visible in scope, restrict retrieval to them. Skipped
// only when the user hand-picked specific docs (N2 — keyed off hasExplicitDocSelection,
// NOT the merged documentIds). Only ever narrows; a live notice names the file(s).
if (!scope.hasExplicitDocSelection) {
const detected = detectFilenameScope(text, documentsInScope(ctx.db, scope, { requireChunks: true }))
if (detected) {
// Narrow to exactly the matched docs (a subset of the resolved scope). `detected.ids`
// come from `documentsInScope(scope)`, which already applied this scope's archived
// filter, so inheriting `includeArchived` by spread keeps the narrowed scope
// CONSISTENT with what surfaced the docs — it never widens visibility (RAG-2). The
// same `buildScopeFilter` then guards retrieval, so there is no archived-leak path.
scope = { ...scope, collectionIds: null, documentIds: detected.ids }
if (!event.sender.isDestroyed()) {
event.sender.send(STREAM.scope(conversationId), { titles: detected.titles })
}
}
}
// Full-doc-skills Phase 3 (§3.2/D44/D46/D47) + A3 (audit §6.3/§8.2): the turn skill's analysis
// handler. It comes from TWO sources, in precedence order:
// 1. the app REGISTRY (`getSkillAnalysisHandler`) — the bank/invoice TOOL skills' exhaustive
// handlers, redaction's routing handler, and the bundled instruction skills' whole-doc/compare
// singletons. Tool handlers are app-only (SEC-1); the registry is that gate.
// 2. A3 fallback: for a skill WITHOUT a registered handler, the MANIFEST's `analysis` engine
// (`manifestAnalysisHandler`) — so a user-imported INSTRUCTION skill declaring
// `analysis: whole-doc`/`compare` reaches the same engine (the fix for "a user-imported skill
// silently gets top-k-with-fence", §6.3). Honored only for `kind:'instruction'`; a user tool
// skill resolves to `undefined` here (it declares no analysis engine and runs no tools — SEC-1).
// When neither yields a handler, or `applies()` is false (off-topic / multi-doc), this whole block is
// skipped and the relevance + coverage-extract paths below run as without a handler (R5), except that a
// bundled whole-document skill's fence carries paragraph 1 only there (#632, #831: `skillFenceMode`).
const turnSkillRecord = skill ? getSkill(ctx.db, skill.installId) : null
const analysisHandler = skill ? skillAnalysisHandler(skill.installId, turnSkillRecord) : undefined
// W2 doc-count-fallthrough routing (audit §2.1/§3.4): a tool/whole-doc skill reads ONE document
// (two, for compare) at a time, so a multi-document scope can't be analysed exhaustively. When the
// turn skill HAS a handler and the question is INTENT-shaped (`intends()`) but `applies()` fails —
// which, given `intends()` is true, can ONLY be the document count — do NOT fall through silently to
// top-k retrieval. Instead narrow to the one document the skill's manifest signals best match (with
// an honest scope notice) or emit a deterministic routing answer. Deterministic, ZERO model calls.
// `intends()` absent (redaction, whose `applies()` already accepts any count ≥ 1) opts out entirely.
let scopeNotice: string | null = null
if (
skill &&
analysisHandler &&
analysisHandler.intends?.({ question: text, scope, db: ctx.db }) &&
!analysisHandler.applies({ question: text, scope, db: ctx.db })
) {
const turnSkill = skill
const inScope = documentsInScope(ctx.db, scope, { requireChunks: true })
// A deterministic routing answer over the LOCKED stream (skill-stamped, no coverage/citations —
// it makes no document claim). Same shape as the refuse/listing paths; no model call. #734 (owner
// call): it records no pack outcome either. It answers nothing, so a ticked pack's "not searched"
// would describe an answer that does not exist.
const routeAnswer = (label: string, answer: string): Promise<Message> =>
withChatStream(
event,
conversationId,
label,
withRegenerateGuard(ctx.db, conversationId, isRegenerate, async (_signal, sendToken): Promise<Message> => {
sendToken(answer)
return appendMessage(ctx.db, {
conversationId,
role: 'assistant',
content: answer,
skillId: turnSkill.installId,
autoFired: turnSkill.autoFired === true
})
}),
(signal) => ctx.docTasks?.acquireChatSlot(signal) ?? Promise.resolve(() => {})
)
if (analysisHandler.mode === 'grounded-whole-doc-compare') {
// what-changed at ≠ 2 docs (audit §3.4): ask for exactly two — the app owns the scope, so this
// replaces the SKILL.md's ask-the-model policing (the model can't see the count). 0 docs stays
// on the ordinary relevance path (its own "no documents" honesty). Only the bundled what-changed
// gets here: a user skill declaring `analysis: compare` has no routing vocabulary, so its
// `intends()` is false and its compare requests at the wrong count fall through (#632 below).
if (inScope.length >= 1) {
return routeAnswer('Document compare routing', tMain('skills.analysis.selectTwo', { count: inScope.length }))
}
} else if (inScope.length >= 2) {
// A single-doc handler over TOO MANY docs: narrow to the ONE the skill's manifest doc signals
// (filenamePatterns/MIME) match. We only narrow to a doc we can ACTUALLY answer exhaustively —
// i.e. one that is FULLY chunked — so the "I answered from «title»" notice is never a lie: a
// sole match that is legacy/partly-chunked would otherwise fall into the refusePartial branch
// below, discarding the notice and implying a single-doc scope the user never chose. In that
// case (or 0 / several matches) we ask the user to pick one instead — the user's pick then
// hits the honest single-doc refusal on its own. Deterministic; no model call.
const triggers = getSkill(ctx.db, turnSkill.installId)?.manifest.triggers
const candidates = triggers ? inScope.filter((d) => matchesSkillDocSignals(triggers, d)) : []
const chosen = candidates.length === 1 ? candidates[0] : null
const narrowedScope = chosen ? { ...scope, collectionIds: null, documentIds: [chosen.id] } : null
if (chosen && narrowedScope && allInScopeDocsFullyChunked(ctx.db, narrowedScope)) {
// Narrow WITHIN the resolved scope (mirrors the filename auto-scope above). `applies()` below
// is now true and the fully-chunked gate passes, so the ordinary dispatch runs and prepends
// `scopeNotice` to its answer (the grounded path carries it via `answerPrefix`).
scope = narrowedScope
scopeNotice = tMain('skills.analysis.scopeNarrowed', { title: chosen.title, count: inScope.length - 1 })
} else {
return routeAnswer('Document analysis routing', tMain('skills.analysis.selectOne', { count: inScope.length }))
}
}
}
// #643 / #642: the one document this turn reads whole instead of top-k, or null (`wholeReadDocumentId`,
// sized for the turn's question and skill). Every caller decides it inside the chat slot, against the
// document as the answer reads it — not before a wait for a yielding document task. #962: sized for the
// fence the turn sends too (`skillFenceMode`, declared below and final before any call), the same budget
// `generateGroundedAnswer` reads the document with, so a "fits" here never becomes a truncated read there.
const wholeReadFor = (treeSummary: boolean): string | null =>
wholeReadDocumentId(
ctx.db,
scope,
documentsInScope(ctx.db, scope, { requireChunks: true }),
text,
wholeDocumentFitBudgetTokens(effectiveContextWindow(runtime, getSettings(ctx.db)), text, skill, skillFenceMode),
treeSummary
)
// What a grounded answer leads with: the W2 scope notice, then (#649) the heads-up that a whole read of a
// total is the model's own arithmetic, which a small model can get wrong even with every section in the
// prompt (design-guidelines §11.24). A top-k sum carries #37's notices instead.
const groundedPrefix = (wholeRead: boolean): string | undefined => {
const lines = [scopeNotice, wholeRead && isTotalAsk(text) ? tMain('analysis.wholeReadSumHint') : null]
const lead = lines.filter((line): line is string => line != null).join('\n\n')
return lead ? `${lead}\n\n` : undefined
}
// #996 A (design-guidelines §11.25): the line that follows that lead when a whole-document map-reduce had
// to cut the document's notes, so the answer covers only its beginning. The core adds it only then.
const beginningNotice = tMain('analysis.wholeDocBeginningOnly')
// A4 (SKA-7 structural, audit §3.2/§8.2): does the turn skill's engine ENGAGE this (possibly
// W2-narrowed) scope? TWO ways in:
// (1) `applies()` — the ordinary gate (a bank/invoice VOCABULARY question, or A3's any-non-chatter
// whole-doc/compare question, over the right doc count); OR
// (2) the TOOL-skill single-doc INVERSION: `applies()` is false (a phrasing MISS) but the ONE
// in-scope FULLY-CHUNKED document plausibly belongs to the skill's class (`classMatches` —
// manifest doc signals or a prior extraction) and the question is NOT small talk. This finishes
// the inversion for bank/invoice: an on-topic money question that misses the ~45-term vocabulary
// is answered from the VERIFIED extract (grounded-data narrates; post-W6 it honestly declines an
// off-data question) instead of silently degrading to raw top-k chunks + model arithmetic (the
// pre-W3 incident class). Only the exhaustive tool handlers define `classMatches`; requiring
// fully-chunked here means a phrasing miss over a legacy/partly-chunked doc falls through to
// relevance (its pre-A4 behaviour), never a refusal. A doc matching NO signal (and with no prior
// extraction) keeps the phrasing gate (the W2 plausibility posture, inverted). No new capability
// and no new model call (SEC-1): it changes WHICH questions reach an already-app-owned handler.
const analysisApplies =
skill != null && analysisHandler != null && analysisHandler.applies({ question: text, scope, db: ctx.db })
const toolSkillInverts =
skill != null &&
analysisHandler != null &&
typeof analysisHandler.classMatches === 'function' &&
!analysisApplies &&
!isSmallTalk(text) &&
allInScopeDocsFullyChunked(ctx.db, scope) &&
analysisHandler.classMatches({ question: text, scope, db: ctx.db }, skill.installId)
// #632 (open-issues wave owner call G-1, option A) and #831 (follow-ups wave 4 owner call G-9), bundled
// skills only (owner round WB2-1): the ONE decision for a BUNDLED whole-document skill (an app skill,
// `source === 'app'`: What Changed?'s compare engine, or the `grounded-whole-doc` engine of Contract
// Brief, Meeting Minutes, Share-Safe Review and Deadline & Obligation Finder) whose engine does not take
// this turn. Three ways that happens:
// 1. `applies()` is false because of the scope: not exactly two answerable documents for the compare
// skill, not exactly one for a whole-document skill, none included (a knowledge-pack-only scope, a
// document still indexing). (An in-vocabulary request at the wrong count never gets this far: the
// W2 pre-pass above narrows it or answers "select two" / "pick one".)
// 2. `applies()` is false because the message is small talk that did not get the short reply above
// (#963, rag-design §19): only a filler question about the last answer ("Sure?") or a bare
// acceptance ("ok") gets here.
// 3. (#831) the whole-document engine applied but sent a single-fact question over a document too long
// to read whole to the passage search (the needle downgrade below sets the mode there).
// The turn falls through to the ordinary grounded answer, where the model sees ordinary passages, not
// the document the skill's format is written for. Its fence then carries paragraph 1 only — the heading
// + honesty rules, `buildSkillFence`'s guaranteed minimum — and not the section format, which a 4B model
// followed even there ("Wer ist der Mieter?" got an "Executive summary" from What Changed?, and full
// minutes from Meeting Minutes for "Who attended?": #831 measured 11 of 16 such answers framed on the
// 4B, 5 of 16 on the 9B, and 0 of 16 on both with paragraph 1 alone). Bundled only, because only there
// is paragraph 1 KNOWN to be those rules (SKA-15, pinned by the SKILL.md parity test): a user skill
// declaring `analysis: compare` or `whole-doc` keeps its whole fence, as before — its paragraph 1 is
// whatever its author wrote, and with no routing vocabulary its real deliverable requests over several
// documents fall through here too. Unchanged: the skill stamp on that answer (fence placed + sections
// found), every path the engine takes (the compare and whole-document reads return below with the whole
// fence), and every other skill's fence. #962: the budgets reserve the fence that is sent, so the room
// paragraph 1 frees goes to the passages (and to `wholeReadFor`'s whole read of one fitting document).
const bundledDeliverableSkill =
turnSkillRecord?.source === 'app' &&
(analysisHandler?.mode === 'grounded-whole-doc-compare' || analysisHandler?.mode === 'grounded-whole-doc')
let skillFenceMode: SkillFenceMode | undefined = bundledDeliverableSkill && !analysisApplies ? 'first-paragraph' : undefined
if (skill && analysisHandler && (analysisApplies || toolSkillInverts)) {
const turnSkill = skill
// The D45/R4 exhaustiveness refusal (fixed localized message + the Re-index affordance, no model,
// no partial answer), skill-stamped so the user sees which skill declined. Closured so BOTH the
// grounded-whole-doc branch (which enforces it only for a non-downgraded whole read — SKA-23) and
// the exhaustive/compare branch reuse one body. A `routing` handler is EXEMPT: it reads no content.
// F2: on regenerate the destructive delete runs inside the runFn (slot held), restored when it
// fails with nothing in its place (#600: any thrown reason) — symmetric with the chat channel.
// #734 (owner call): no pack outcome. The refusal makes no document claim, so there is no answer
// for a ticked pack's "not searched" to qualify.
const refusePartial = (): Promise<Message> =>
withChatStream(
event,
conversationId,
'Document analysis refused',
withRegenerateGuard(ctx.db, conversationId, isRegenerate, async (_signal, sendToken): Promise<Message> => {
const refusal = tMain('skills.analysis.refusePartial')
sendToken(refusal)
return appendMessage(ctx.db, {
conversationId,
role: 'assistant',
content: refusal,
skillId: turnSkill.installId,
autoFired: turnSkill.autoFired === true
})
}),
(signal) => ctx.docTasks?.acquireChatSlot(signal) ?? Promise.resolve(() => {})
)
// `grounded-whole-doc` (skill-whole-doc engine, Wave 2): an INSTRUCTION skill whose deliverable is
// the MODEL's answer over the WHOLE document, formatted to the SKILL.md body (minutes, contract
// brief, …). Stream a grounded answer where the context is the single in-scope document read IN
// ORDER (not top-k) with the fence applied; coverage is the honest `capped` mode. `applies()`
// guaranteed a single in-scope doc. SKA-23 (A4): the D45 refusal is evaluated INSIDE this branch,
// AFTER the needle downgrade — so a downgraded needle reaches top-k rather than a refusal.
if (analysisHandler.mode === 'grounded-whole-doc') {
const target = documentsInScope(ctx.db, scope, { requireChunks: true })[0]
if (target) {
const documentId = target.id
// A3 needle-vs-deliverable downgrade (audit §8.2 (b)) + SKA-12/SKA-23 (A4). The whole-doc engine
// is the DEFAULT, but a targeted single-fact LOOKUP over a document that would OVERFLOW the
// whole-doc budget is better served by top-k — a needle past the truncation cut would be missed,
// where relevance retrieval finds the passage wherever it sits. Reuses W1's exact budget calculus
// (the de-overlapped token total vs `wholeDocumentFitBudgetTokens`). A DELIVERABLE ask never
// downgrades — it keeps the whole read (W1's honest capped/tree path).
// - SKA-12: the `readyTreeCountInScope === 0` conjunct is GONE. A needle prefers top-k whenever
// the whole read would truncate, TREE OR NO TREE: a ~13-call map-reduce over lossy node
// summaries is worse for a single-fact lookup than one top-k retrieval (the tree keeps
// rescuing DELIVERABLES, which never reach this downgrade).
// - SKA-23: this is evaluated BEFORE the D45 fully-chunked refusal below. A downgraded needle
// takes the relevance path, which makes NO whole-document claim, so D45's premise (a partial
// WHOLE read passed off as complete) doesn't apply — a needle over a not-fully-chunked doc is
// served by top-k, not refused. A DELIVERABLE keeps the whole read and DOES hit the refusal.
// - #962: this budget stays sized for the WHOLE fence (no `fenceMode`): it asks whether the engine's
// own read, which carries the whole fence, would truncate. Only after a downgrade does the turn
// carry paragraph 1, and the budgets of that fall-through reserve paragraph 1.
const needleDowngrade =
isNeedleShaped(text) &&
!documentFitsWholeRead(
ctx.db,
documentId,
wholeDocumentFitBudgetTokens(effectiveContextWindow(runtime, getSettings(ctx.db)), text, turnSkill)
)
if (!needleDowngrade) {
// Only a whole (capped/tree) read makes the whole-document claim → enforce the D45 refusal now.
if (!allInScopeDocsFullyChunked(ctx.db, scope)) return refusePartial()
return withChatStream(
event,
conversationId,
'Document answer failed',
withRegenerateGuard(ctx.db, conversationId, isRegenerate, (signal, sendToken, _sendReasoning, sendCompaction, sendUsage) =>
generateGroundedAnswer(ctx.db, runtime, ctx.embedder, conversationId, text, settings, {
signal,
onCompactionStart: sendCompaction,
// The real assembled-prompt usage (incl. the whole-document block) for the meter.
onPromptUsage: sendUsage,
scope,
reranker: ctx.reranker,
// The turn's skill fence rides in the grounded USER turn; the whole document is the
// context, so the assistant row carries the skill stamp + `capped` coverage.
skill: turnSkill,
wholeDocument: { documentId },
// U2 (audit §3.5): share-safe review injects a deterministic whole-document PII count
// summary into the prompt and gates its low-risk verdict on non-truncated coverage.
wholeDocumentPiiScan: analysisHandler.injectPiiScan === true,
// #939, #953 (owner calls 2026-11-20, waves 4 and 5 G-2): over a document too long for one
// call, the map and fold steps take notes for the question too, under a bundled skill and
// the user's own alike, unless it asks for the skill's report: a summary, minutes, a brief, a
// review or the summarize chip, list word or not (`isReportShaped`), or what the router reads
// as a summary (`asksForSummary`: the split verb of «Fasse alle Beschlüsse zusammen»). Those
// keep master's prompts, byte for byte. The skill's fence already writes its report in every
// map step; the question keeps a non-report one ("Tell me about the parking rules", a user
// skill's "List every deadline") from being answered from notes for the report
// (rag-design §14.10).
wholeDocumentNotesForRequest: !isReportShaped(text) && !asksForSummary(text),
onToken: sendToken,
// W2 (§2.1): when the scope was auto-narrowed to this doc, lead the streamed + persisted
// answer with the honest scope notice (undefined ⇒ byte-unchanged). #649: a total leads with
// the arithmetic heads-up too — this is a whole read.
answerPrefix: groundedPrefix(true),
// #996 A: and a document too long to read in full says so after them.
beginningNotice
})),
(signal) => ctx.docTasks?.acquireChatSlot(signal) ?? Promise.resolve(() => {})
)
}
// needleDowngrade: fall through to the relevance (top-k) path below — no refusal (SKA-23). #831: the
// engine declined this turn, so a bundled skill's fence carries paragraph 1 only there (the decision
// above). A downgraded needle that lands on the coverage-extract listing carries no fence at all.
if (bundledDeliverableSkill) skillFenceMode = 'first-paragraph'
}
// Defensive: applies() requires a single in-scope doc, so a missing target is unreachable; fall
// through to the relevance path rather than fail the turn.
} else {
// exhaustive (bank/invoice) / compare / routing: the D45 refusal gates FIRST (routing exempt — it
// reads no content), then the mode dispatch. (grounded-whole-doc handled its own refusal above.)
if (analysisHandler.mode !== 'routing' && !allInScopeDocsFullyChunked(ctx.db, scope)) {
return refusePartial()
}
// `grounded-whole-doc-compare` (Follow-up B, what-changed): a compare-shaped request over
// EXACTLY TWO in-scope docs streams a model answer over BOTH documents read whole (budget
// split across them) with the fence applied; coverage is `capped` (truncated when either
// overflowed). `applies()` guaranteed exactly two in-scope docs; the fully-chunked refusal
// above already gated both. (Needle downgrade stays single-doc — compare keeps its whole-both
// read; existing residual, audit §3.3.)
if (analysisHandler.mode === 'grounded-whole-doc-compare') {
// The shared helper's deterministic `ORDER BY created_at, id` fixes the compare PAIR order
// (audit §5.1): `[0]`→Document A, `[1]`→Document B is now import-order-stable, not the
// undefined SQL row order the old private query left it. The prompt labels the pair A/B by
// title + import date and NEVER asserts which is the older/newer version, so a wrong guess
// can no longer invert a whole report.
const documentIds = documentsInScope(ctx.db, scope, { requireChunks: true }).map((d) => d.id)
if (documentIds.length === 2) {
return withChatStream(
event,
conversationId,
'Document answer failed',
withRegenerateGuard(ctx.db, conversationId, isRegenerate, (signal, sendToken, _sendReasoning, sendCompaction, sendUsage) =>
generateGroundedAnswer(ctx.db, runtime, ctx.embedder, conversationId, text, settings, {
signal,
onCompactionStart: sendCompaction,
onPromptUsage: sendUsage,
scope,
reranker: ctx.reranker,
skill: turnSkill,
wholeDocumentCompare: { documentIds },
// #649: both documents are read whole, so a total leads with the arithmetic heads-up.
answerPrefix: groundedPrefix(true),
onToken: sendToken
})),
(signal) => ctx.docTasks?.acquireChatSlot(signal) ?? Promise.resolve(() => {})
)
}
// Defensive: applies() requires exactly two in-scope docs; otherwise fall through.
}
// `exhaustive` / `routing`: auto-run the read-only whole-document tools (D46) and persist the
// exhaustive answer with its honest extract/whole coverage (D48) + real citations, OR (routing)
// return the action-routing answer. NO model call — deterministic, localized copy (D47). A
// `grounded-whole-doc` handler omits `run()` and returned above; the guard keeps types honest.
if (analysisHandler.run) {
const runHandler = analysisHandler.run.bind(analysisHandler)
const notice = scopeNotice
return withChatStream(
event,
conversationId,
'Document analysis failed',
withRegenerateGuard(ctx.db, conversationId, isRegenerate, async (signal, sendToken, _sendReasoning, sendCompaction, sendUsage): Promise<Message> => {
// U5 (audit §3.6): the exhaustive path runs a potentially long, SILENT deterministic
// extraction before the first token — a "one-blob" answer that reads as a hang. Fire the
// ephemeral "reading the document…" notice up front (the compaction-notice channel, an
// 'analysis' kind); the renderer clears it on the first answer token, exactly like the
// compaction hint. Ephemeral (R14) — never buffered, never persisted.
sendCompaction('analysis')
const result = await runHandler({
db: ctx.db,
question: text,
scope,
skillInstallId: turnSkill.installId,
conversationId,
// The app's real ids/counts-only audit sink (the skills-run adapter — never invent one).
audit: toSkillToolAudit(ctx.audit),
// Thread the chat slot's abort signal so Cancel stops the auto-run.
signal,
tr: (key, params) => tMain(key, params),
// Faithful newline-preserving segments (not the overlap-collapsing chunks table).
readDocumentSegments,
// The chat slot's runtime — for the one sanctioned inline model sub-step (a
// prompt-supplied custom category set, result-tables Phase 1.5); see the ctx type.
runtime
})
// W2 plausibility gate (audit §4.5): the extractor found nothing on a document that doesn't
// look like this skill's type — answer the user's ACTUAL question via the ordinary grounded
// (relevance) path in the SAME locked slot, instead of the misleading empty template. The
// turn's skill fence still rides along (parity with the ordinary document path below).
// #643: like that path, a document that fits is read whole instead of top-k. #649: and like it,
// the answer leads with the W2 scope notice and a whole-read total's heads-up.
if (result.fallThrough) {
const wholeReadId = wholeReadFor(false)
return generateGroundedAnswer(ctx.db, runtime, ctx.embedder, conversationId, text, settings, {
signal,
onCompactionStart: sendCompaction,
onPromptUsage: sendUsage,
scope,
reranker: ctx.reranker,
skill: turnSkill,
wholeDocument: wholeReadId ? { documentId: wholeReadId } : undefined,
answerPrefix: groundedPrefix(wholeReadId != null),
beginningNotice,
onToken: sendToken
})
}
// W3 THIRD answer mode (audit §3.1/§8.1): the question is neither a format ask nor a
// summary/reconcile/list shape, so instead of the fixed template the handler returned the
// serialized VERIFIED extract — stream a model answer that NARRATES it (strict verbatim
// rules, in the SAME locked slot), with the deterministic totals echoed beneath it. The
// turn's skill fence + honest extract coverage/citations ride along (parity with the paths
// above). The LLM never computes a figure; it reads the data the deterministic tools built.
if (result.mode === 'grounded-data') {
return generateGroundedDataAnswer(
ctx.db,
runtime,
conversationId,
text,
{
dataBlock: result.dataBlock ?? '',
postscript: result.postscript ?? '',
citations: result.citations,
coverage: result.coverage
},
{
signal,
onCompactionStart: sendCompaction,
onPromptUsage: sendUsage,
onToken: sendToken,
skill: turnSkill,
// W2 (§2.1): carry the auto-narrow scope notice into the grounded-data path too.
answerPrefix: notice ? `${notice}\n\n` : undefined,
// Knowledge packs (#301 P4, plan §9.21 (e)5): this path narrates a
// deterministic extract from DOCUMENTS and never queries a pack, so every
// ticked pack gets an honest `skipped / mode` outcome. Built HERE because
// `GroundedDataAnswerOptions` carries no scope — the resolved one lives here.
packOutcomes: modePackOutcomes(ctx.db, scope.packIds)
}
)
}
// W2 (§2.1): when the scope was auto-narrowed to this doc, prepend the honest notice.
const answer = notice ? `${notice}\n\n${result.answer}` : result.answer
sendToken(answer)
const msg = appendMessage(ctx.db, {
conversationId,
role: 'assistant',
content: answer,
citations: result.citations,
coverage: result.coverage,
skillId: turnSkill.installId,
autoFired: turnSkill.autoFired === true,
// #734 (#301 P4): the template answer is built from the document by the skill's tools and
// never queries a pack, like the grounded-data narration above, so every ticked pack is
// told `skipped / mode`. A `routing` handler's button pointer (redaction, document edit)
// reads no content and makes no document claim: none, like the W2 routing answer.
packOutcomes: analysisHandler.mode === 'routing' ? undefined : modePackOutcomes(ctx.db, scope.packIds)
})
// Phase 2 (result-tables §4): persist the answer's structured table keyed by the
// just-appended message and light the flag on the returned object, so the renderer's
// "Export CSV" action shows without a reload. Best-effort — a table that fails to
// persist (over-cap / serialization fault) never blocks the answer itself.
if (result.table) {
try {
if (saveResultTable(ctx.db, {
messageId: msg.id,
conversationId,
table: result.table,
source: turnSkill.installId
})) {
msg.hasResultTable = true
}
} catch {
log.warn('Result-table persist failed', { messageId: msg.id })
}
}
return msg
}),
(signal) => ctx.docTasks?.acquireChatSlot(signal) ?? Promise.resolve(() => {})
)
}
}
}
// Task router (whole-document-analysis plan §4.4, Phase 3): a "list every X / how many"
// question over a mapped, PRE-EXTRACTED type is answered by the precomputed SQL
// aggregation — exhaustive over indexed sections, with provenance, at ZERO query-time
// model calls (#649: an aggregation ask over one fitting document is read whole instead).
// Anything else (incl. an unmapped/ad-hoc {X} with no precomputed table)
// falls through to the final grounded answer below: the relevance path, or the whole
// read of a single fitting document (#643 / #642).
const routableDocs = documentsInScope(ctx.db, scope, { requireChunks: true })
const routeInput = {
question: text,
documentCount: routableDocs.length,
treeAvailable: readyTreeCountInScope(ctx.db, scope) > 0,
extractAvailable: extractionsExistInScope(ctx.db, scope)
}
const decision = routeQuestion(routeInput)
// #80 P3 (STR-1 §5.2): the ONE bounded skill-pointer classification, run ONLY on the two
// trigger classes `isClassificationTrigger` pins — (a) aggregation-shaped coverage-extract
// turns, (b) low-confidence fallbacks — INSIDE the already-held chat slot, BEFORE the answer
// is emitted. It never changes the engine, never activates a skill, and its output never
// reaches answer content: it only fills the per-answer OFFER surface (provenance
// 'classifier'; a user click is the consent, S13b/D4). Candidates are the ONE shared offer
// gate minus the skill that already shaped this turn; every fault degrades to null (no
// offer) inside a hard few-second bound — the mock runtime always degrades, so mock/dev
// behaviour is byte-identical to today. Ordinary high-confidence questions never get here
// (0 model calls preserved by construction).
// #133: would OFFERING this candidate be honest — i.e. would the accept click (regenerate with
// the skill explicitly set) actually produce a skill-shaped turn? Mirrors the dispatch gate
// above over the SAME (possibly narrowed) scope: a candidate with no analysis handler is an
// instruction skill whose fence shapes the prompt (always honestly stamped); a tool/analysis
// candidate engages when its `intends()` is true (the W2 pre-pass then handles a doc-count miss
// HONESTLY — narrowing or a routing answer, never a silent no-op), when `applies()` is true, or
// via the A4 classMatches inversion. Without this check an accepted offer whose handler misses
// the question re-ran the SAME engine, stamped the skill's provenance glyph on an answer its
// engine never touched, and re-classified with that skill excluded — offer ping-pong.
// #733: the W2 pre-pass acts only on an answerable document in scope, so `intends()` counts only then;
// with documents off or nothing indexed the accept would re-run the same answer under the skill's stamp.
const wouldSkillEngage = (installId: string): boolean => {
const record = getSkill(ctx.db, installId)
if (!record) return false
const handler = skillAnalysisHandler(installId, record)
if (!handler) return true
const input = { question: text, scope, db: ctx.db }
if (routableDocs.length > 0 && handler.intends?.(input) === true) return true
if (handler.applies(input)) return true
return (
typeof handler.classMatches === 'function' &&
!isSmallTalk(text) &&
allInScopeDocsFullyChunked(ctx.db, scope) &&
handler.classMatches(input, installId)
)
}
const classifierOffer = async (signal: AbortSignal, routed: RouteDecision): Promise<SkillOffer | null> => {
if (!isClassificationTrigger(routed, text)) return null
// #733: with no section in scope and no pack (documents off, an empty project, a document that never
// indexed) every answer is the fixed no-context reply, which no skill changes.
if (!scope.packIds?.length && !sectionsExistInScope(ctx.db, scope)) return null
// Candidates = the shared offer gate, minus the turn's own skill, minus (#133) any skill
// whose engine would NOT engage this question+scope — an offer must be a real capability,
// not a provenance-stamped re-run of the same answer.
const candidates: ClassifyCandidate[] = offerableSkillCandidates(ctx.db, ctx.skills?.appVersion ?? '')
.filter((c) => c.installId !== skill?.installId && wouldSkillEngage(c.installId))
.map((c) => ({ installId: c.installId, title: c.title }))
const picked = await classifySkillPointer(text, candidates, { runtime, signal })
return picked ? { installId: picked.installId, title: picked.title, source: 'classifier' } : null
}
// Issues #37/#38: the router WANTED the whole-document coverage engine (a list/count/
// aggregation question) but no extract data exists in scope, so it fell back to top-k
// relevance. That fallback used to be silent — `decision.confidence` was computed and
// discarded, so a categorization/sum answer over 5 of 25 sections read like any normal
// answer. Lead the answer with the actionable hint (build the deep index) instead. It
// streams first and persists with the content, after the W2 scope notice; gated on ≥1
// answerable doc so an empty-scope turn keeps its own "no documents" honesty path unchanged.
// #641: the hint is decided AFTER retrieval (`partialCoverageNotice`) — it shows only when
// the answer read fewer sections than the scope holds. A short document whose sections all
// reached the prompt has nothing for the deep index to add. A `partial` fallback (an
// explain request or an untyped {X} with a quantifier) gets the same label WITHOUT the
// deep-index advice: the deep index would not answer it either. A document in scope that
// was never fully chunked (legacy) has text no section holds, so it always counts as
// partly read.
//
// #643 / #642: ONE in-scope document that fits the window is read whole instead (every
// section in the prompt, so neither notice can be true), and a summary ask over one document
// too large for that, with a ready deep index, takes the tree. See `wholeReadDocumentId`.
// Both are decided inside the chat slot (below), against the document as the answer reads
// it — not before a wait for a yielding document task.
const partialCoverageNoticeFor = (
wholeRead: boolean,
routed: RouteDecision
): GroundedAnswerOptions['partialCoverageNotice'] => {
const scopeSections =
!wholeRead &&
routed.confidence === 'low' &&
(routed.fallback === 'coverage' || routed.fallback === 'partial') &&
routableDocs.length > 0
? scopeSectionTotals(ctx.db, scope)
: null
return scopeSections
? {
text: tMain(routed.fallback === 'coverage' ? 'analysis.wholeDocHint' : 'analysis.partialAnswerHint'),
scopeChunkTotal: scopeSections.partlyChunked ? Number.POSITIVE_INFINITY : scopeSections.sections,
scopeDocumentIds: scopeSections.documentIds
}
: undefined
}
// The grounded answer: top-k relevance, or the whole read of `wholeReadId` (#643 / #642; #649: also an
// aggregation ask the router sent to coverage-extract). The offer is attached to the persisted answer
// afterwards (update-in-place of the offer column only) — it never touches the answer content or the
// stream — unless the answer is the fixed no-context reply and the offered skill is fence-only (#779).
const groundedAnswer = async (
signal: AbortSignal,
sendToken: SendToken,
sendCompaction: SendCompaction,
sendUsage: SendUsage,
wholeReadId: string | null,
offer: SkillOffer | null,
routed: RouteDecision
): Promise<Message> => {
const msg = await generateGroundedAnswer(ctx.db, runtime, ctx.embedder, conversationId, text, settings, {
signal,
// One-shot ephemeral "summarizing…" notice when the compaction pre-pass starts (§5.2);
// isDestroyed-guarded inside withChatStream, never buffered (R14).
onCompactionStart: sendCompaction,
// The real assembled-prompt usage (incl. the retrieved excerpt block) for the meter.
onPromptUsage: sendUsage,
// Composite retrieval scope (plan §10.2): membership ∪ specific docs ∪ attachments,
// archived excluded by default. Also makes the empty-context re-index check
// scope-aware (M2). An empty resolved scope = whole corpus.
scope,
// Retrieval reranker: null when no reranker is provisioned — retrieval then
// keeps the unreranked ordering byte-identical.
reranker: ctx.reranker,
// Knowledge packs (ZIM wave): the query-time archive arm, only when this chat's
// scope selected packs (opt-in per chat). makeArm returns null when the tools
// are missing or nothing is retrievable; retrieve() isolates arm failures.
// #340 L3-b (D-Z20, owner ruling 2026-09-07 "always"): the arm expands the question
// through the turn's own runtime — one short, bounded, grammar-constrained call per
// pack-scoped ask, before the search; any failure falls back to the plain pattern.
// Step 4-4 (ruling (a)): `candidateScope` widens what the arm admits on a `gpu`/
// opted-in `cpu-hi` machine; absent reranker or `default` profile it is `'capped'`,
// byte-identical to today.
externalArm:
ctx.zim?.makeArm(ctx.db, scope.packIds, {
expand: makeQueryExpander(runtime),
candidateScope
}) ?? null,
// The turn's skill: its fence rides in the grounded user turn; the assistant row is
// stamped only when the fence fit AND chunks were found (no-context ⇒ NULL).
skill,
// #632 / #831: paragraph 1 only for a bundled whole-document skill whose engine did not take the turn.
skillFenceMode,
// #643 / #642: the one document read whole (or through its ready deep index) instead
// of top-k — `capped`/`tree` coverage; the pack arm and the notice below are top-k only.
wholeDocument: wholeReadId ? { documentId: wholeReadId } : undefined,
// A3: a needle ask that was auto-narrowed to one doc (W2) and then downgraded off the
// whole-doc engine reaches HERE — lead the honest scope notice so the narrowing stays
// visible. #37/#38/#641: the whole-document-question hint or the partial-answer label
// (composed above) follows it when retrieval left sections out. Both are absent on
// every ordinary route into this path (byte-unchanged). #649: a whole read of a total
// leads with its own heads-up after the scope notice.
answerPrefix: groundedPrefix(wholeReadId != null),
// #996 A: a deep-index read (#642) whose notes had to be cut covers only the beginning and says so.
beginningNotice,
partialCoverageNotice: partialCoverageNoticeFor(wholeReadId != null, routed),
onToken: sendToken
})
// #779: the offer is classified BEFORE retrieval, so retrieval can still end in the fixed no-context
// (or re-index) reply. A fence-only skill re-runs the same top-k search under its fence: accepting it
// would only bring back that fixed reply, so it is not offered there. A skill with an analysis engine
// stays offered — its engine reads beyond top-k.
const fenceOnlyOnNoContext =
offer != null &&
isNoContextAnswer(msg.content) &&
skillAnalysisHandler(offer.installId, getSkill(ctx.db, offer.installId)) == null
if (offer && !fenceOnlyOnNoContext) {
setMessageSkillOffer(ctx.db, msg.id, offer)
msg.skillOffer = offer
}
return msg
}
if (decision.engine === 'coverage-extract' && decision.recordType) {
const recordType: ExtractRecordType = decision.recordType
// A3: a needle ask under an active whole-doc skill can be DOWNGRADED off the whole-doc engine
// (grounded-whole-doc block above) and land HERE — and it may have been auto-narrowed by the W2
// pre-pass first (`scopeNotice` set, `scope` reduced to one doc). Lead the honest scope notice so a
// per-doc count never reads as covering the whole multi-doc scope, and stamp the skill so the turn
// keeps its provenance glyph (A1). `scopeNotice` is null and `skill` undefined on every ordinary
// (non-skill / non-narrowed) coverage-extract turn, so this is byte-unchanged there.
// #54: an aggregation-shaped ask (categorize / group by / sum per …) is deliberately
// routed here (#37 — never a silent top-k sum), but this engine can only list values
// with counts. The renderer leads such an answer with an honest shape hint (+ the
// bank-statement-skill pointer for `amount`) so a frequency list is never presented
// as the requested categories/sums.
const aggregationAsk = isAggregationShaped(text)
// #80 P1 — the ACTIONABLE sibling of the #54 prose hint: an aggregation-shaped `amount`
// ask served by this list-only engine gets a wrong-shaped answer, and the hint already
// points at the bank-statement skill. Attach the skill as a one-click OFFER on the answer
// (deterministic — no model): the click re-runs the turn with the skill (regenerate +
// explicit skillInstallId; click = consent, S13b/D4 — auto-fire stays OFF). Gated on the
// ONE shared candidate gate (enabled + available + app-compatible) and never offered for
// the skill that already shaped this turn. The prose hint STAYS as the degradation path
// (offer gated out / older renderer).
let deterministicOffer: SkillOffer | null = null
if (aggregationAsk && recordType === 'amount' && skill?.installId !== BANK_STATEMENT_INSTALL_ID) {
const bank = offerableSkillCandidates(ctx.db, ctx.skills?.appVersion ?? '').find(
(c) => c.installId === BANK_STATEMENT_INSTALL_ID
)
// #133: only offer bank when its engine would actually ENGAGE the accept (an aggregation-
// shaped amount ask is category-shaped, so `intends()` normally holds — this guards the
// residual class where it wouldn't, e.g. an exotic phrasing over a scope its handler
// cannot serve; the prose hint remains as the degradation).
if (bank && wouldSkillEngage(bank.installId)) {
deterministicOffer = { installId: bank.installId, title: bank.title, source: 'deterministic' }
}
}
return withChatStream(
event,
conversationId,
'Document listing failed',
withRegenerateGuard(ctx.db, conversationId, isRegenerate, async (signal, sendToken, _sendReasoning, sendCompaction, sendUsage): Promise<Message> => {
// #80 dedupe (owner decision 4): the deterministic offer WINS — the classifier runs
// only when the rule produced nothing (non-amount aggregation asks / bank gated out),
// so the two sources can never double-offer. The listing itself stays deterministic;
// only aggregation-shaped turns pay the one bounded classification call (plain
// list/count turns keep 0 model calls). Classified BEFORE the answer is emitted.
const offer = deterministicOffer ?? (aggregationAsk ? await classifierOffer(signal, decision) : null)
// #649: an aggregation ask (a sum, categories) over ONE document that fits the window is read
// whole instead (#643's rule, decided here in the slot): the model sees every section and can add
// them up, which the listing cannot (#54). The offer above rides along. A plain list ask keeps the
// listing, and so does a document too long to read whole.
const wholeReadId = aggregationAsk ? wholeReadFor(false) : null
if (wholeReadId) return groundedAnswer(signal, sendToken, sendCompaction, sendUsage, wholeReadId, offer, decision)
const listing = aggregateExtractions(ctx.db, scope, recordType)
const listingAnswer = buildListingAnswer(ctx.db, listing, (key, params) => tMain(key, params), {
aggregationAsk
})
const answer = scopeNotice ? `${scopeNotice}\n\n${listingAnswer}` : listingAnswer
sendToken(answer)
return appendMessage(ctx.db, {
conversationId,
role: 'assistant',
content: answer,
skillId: skill?.installId,
autoFired: skill?.autoFired === true,
skillOffer: offer,
// #734 (#301 P4): the listing is built from the documents' extract and never queries a
// pack, so every ticked pack gets `skipped / mode` rather than looking like it found nothing.
packOutcomes: modePackOutcomes(ctx.db, scope.packIds)
})
}),
// Acquire the slot so a yielding deep-index build is paused/resumed cleanly even
// though we make no model call (keeps the single locked contract).
(signal) => ctx.docTasks?.acquireChatSlot(signal) ?? Promise.resolve(() => {})
)
}
return withChatStream(
event,
conversationId,
'Document answer failed',
// F2: defer the regenerate delete into the runFn (slot held) + restore when it fails (#600: any reason).
withRegenerateGuard(ctx.db, conversationId, isRegenerate, async (signal, sendToken, _sendReasoning, sendCompaction, sendUsage) => {
// #736: a `tree-summary` route holds only when the tree (or a whole read of the one document) answers,
// decided here, before the classification a tree route never runs. Anywhere else top-k answers, so the turn
// is labelled and classified as the router routes it without the deep index: several documents, a chat
// with knowledge packs, a document whose own deep index cannot answer.
const treeRoute = decision.engine === 'tree-summary'
const treeRead = treeRoute ? wholeReadFor(true) : null
const routed = treeRoute && treeRead == null ? routeQuestion({ ...routeInput, treeAvailable: false }) : decision
// #80 P3 trigger (b): a LOW-CONFIDENCE fallback (the router detected an intent it
// provably cannot serve — a coverage ask with no extract data, a compare without two
// docs) runs the one bounded classification BEFORE the grounded answer streams; a
// high-confidence relevance turn returns null here WITHOUT a model call (the step-5
// fallthrough never classifies). The offer is attached to the persisted answer
// afterwards (update-in-place of the offer column only) — it never touches the
// answer content or the stream.
const offer = await classifierOffer(signal, routed)
return groundedAnswer(signal, sendToken, sendCompaction, sendUsage, treeRoute ? treeRead : wholeReadFor(false), offer, routed)
}),
(signal) => ctx.docTasks?.acquireChatSlot(signal) ?? Promise.resolve(() => {})
)
}
)
}