From 7ced9e0ca3b9d3def2c1318a0d414ba1e539efde Mon Sep 17 00:00:00 2001 From: Ambisphaeric <270742616+Ambisphaeric@users.noreply.github.com> Date: Fri, 17 Jul 2026 20:14:50 -0400 Subject: [PATCH] feat(distill): human note-taking voice + silence for empty windows (#245) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rewrite the summary-family prompt bodies (distill window notes + the five hierarchical levels) into a human note-taking register: lead with the substance, ban transcription-narration framings ("The speaker expressed…", "The transcript indicates…"), keep the invent-nothing honesty rules, stay terse. Add three silence-over-noise drops so an empty window persists no distillate: a cheap deterministic pre-gate on observed window material (DISTILL_MIN_CHARS, deliberately low — the sentinel does the substance judgment), a model escape that drops the window on an exact NOTHING_NOTEWORTHY response (embedded token is kept), and an empty/ whitespace-only response drop at the same site. Summary bodies auto-upgrade for unedited installs via the existing PREVIOUS_BUILTIN_BODIES refresh; user edits are never clobbered. The distill and summary contract example JSONs are updated so the "Mirrors" comments stay true. Closes #245 --- apps/engine/src/distill/defaults.ts | 196 +++++++++++------ apps/engine/src/distill/distiller.ts | 41 +++- apps/engine/src/distill/documents.test.ts | 75 ++++++- apps/engine/src/distill/documents.ts | 12 +- apps/engine/src/distill/guard.test.ts | 2 +- .../src/distill/preset-injection.test.ts | 4 +- apps/engine/src/distill/suppression.test.ts | 208 ++++++++++++++++++ .../examples/promptTemplate.distill.json | 4 +- .../examples/promptTemplate.summary.json | 2 +- 9 files changed, 451 insertions(+), 93 deletions(-) create mode 100644 apps/engine/src/distill/suppression.test.ts diff --git a/apps/engine/src/distill/defaults.ts b/apps/engine/src/distill/defaults.ts index 081d4abf..9e7bfe8d 100644 --- a/apps/engine/src/distill/defaults.ts +++ b/apps/engine/src/distill/defaults.ts @@ -1,13 +1,24 @@ import type { Mode, PromptTemplate } from '@openinfo/contracts' +/** + * The exact sentinel a SUMMARY-family template emits when a window holds nothing worth noting — the + * model-level half of the silence-over-noise gate (#245). Defined here, next to the template bodies that + * embed it, and imported by the distiller that drops on it, so the instruction text and the drop check can + * never silently drift apart. Drop semantics are EXACT: the engine drops only when the whole trimmed model + * response equals this token (case-sensitive) — a sentinel embedded inside a real note does NOT count. + */ +export const NOTHING_NOTEWORTHY = 'NOTHING_NOTEWORTHY' + /** * The shipped distill prompt template — a document, not a hardcoded preset (glass mistake left - * behind). The FACTORY default is neutral (#130): a short, factual rolling-merge summary that keeps - * only the load-bearing parts (output grammar, invent-nothing rule, {{transcript}}/{{windowStart}}/ - * {{windowEnd}} window interpolation) and bakes NO persona/voice dials. The voice-vector machinery - * (compileVoiceVars → {{tone}}…{{voice.rules}}) is still live for a user-authored/edited template — - * it is simply not pre-tweaked into the shipped body. Mirrors - * shared/contracts/examples/promptTemplate.distill.json. + * behind). The FACTORY default is neutral of persona dials (#130: no baked voice vector — the voice + * machinery `compileVoiceVars → {{tone}}…{{voice.rules}}` stays live for a user-authored/edited template, + * it is simply not pre-tweaked into the shipped body) but is deliberately OPINIONATED about REGISTER (#245): + * generic small models, given "a tight, factual summary", default to meeting-minutes report-speak that + * narrates the act of transcription ("The speaker expressed…", "The transcript indicates…"). The body + * instead pins the human note-taking register — lead with the substance, banned narration framings, terse — + * and keeps the load-bearing parts (invent-nothing honesty, {{transcript}}/{{windowStart}}/{{windowEnd}} + * interpolation, the NOTHING_NOTEWORTHY escape). Mirrors shared/contracts/examples/promptTemplate.distill.json. */ export const defaultDistillTemplate: PromptTemplate = { id: 'tpl-distill-default', @@ -15,11 +26,15 @@ export const defaultDistillTemplate: PromptTemplate = { kind: 'distill', slot: 'llm', builtin: true, - description: 'rolling-merge summary; neutral factual default (no baked voice vector — dials remain available to edited templates)', + description: 'rolling-merge window notes; human note-taking register, silence when nothing was said (no baked voice vector — dials remain available to edited templates)', body: - 'You are distilling a live meeting into a tight, factual summary of what just happened.\n' + - 'Summarize only what the transcript supports. Do not invent commitments or names.\n\n' + - 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nSummary:', + 'Jot the notes a sharp colleague would take on this stretch of a live meeting — the substance, nothing more.\n' + + '- Lead with the fact itself. Write "Feedback to QA — due soon", not "The speaker expressed a goal to provide feedback".\n' + + '- Never narrate the transcript. Do not open with "the speaker said/expressed/stated", "the transcript indicates/shows", or "it was mentioned/noted/recorded/discussed" — write the thing, not the fact that it was said.\n' + + '- Keep only what the transcript supports: no invented commitments, names, numbers, or motives.\n' + + '- Terse: the fewest words that carry it. No preamble, no framing, no sign-off.\n' + + '- If nothing here is worth a note — only filler, fragments, or garble — reply with exactly ' + NOTHING_NOTEWORTHY + ' and nothing else.\n\n' + + 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nNotes:', } /** @@ -79,50 +94,6 @@ export const defaultEntitiesTemplate: PromptTemplate = { 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nJSON array of entities:', } -/** - * The PREVIOUS shipped bodies of the three window templates — the voice-baked bodies that shipped - * before #130 made the factory defaults neutral. The one-time builtin-body refresh - * (DistillDocuments.ensureDefaults) uses these to detect an UNEDITED builtin on an existing install: - * seeds are seed-if-absent, so an upgrader keeps its old baked body forever otherwise. A stored - * builtin is treated as unedited — and refreshed to the new neutral body — ONLY when it is still at - * version 1 AND its body is byte-for-byte one of these previous bodies. Any user edit bumps the - * version off 1 (LayoutStore.put) and/or diverges the body, so an edited document is NEVER clobbered. - * Keyed by template id. Keep in lockstep with the bodies above: a refresh compares against these, - * never against the current body. - */ -export const PREVIOUS_BUILTIN_BODIES: Readonly> = { - [defaultDistillTemplate.id]: - 'You are distilling a live meeting into a tight, factual summary of what just happened.\n' + - 'Voice: tone {{tone}}/10, warmth {{warmth}}/10, wit {{wit}}/10, charm {{charm}}/10, ' + - 'specificity {{specificity}}/10, brevity {{brevity}}/10.\n' + - '{{voice.rules}}\n' + - 'Summarize only what the transcript supports. Do not invent commitments or names.\n\n' + - 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nSummary:', - [defaultExtractTemplate.id]: - 'You extract typed moments from a meeting transcript. Return ONLY a JSON array, no prose, no code fences.\n' + - 'Each element: {"kind": one of "commitment"|"question"|"decision"|"artifact", "text": string, ' + - '"speaker": string (optional), "confidence": number 0..1 (optional), "answered": boolean (only for kind "question")}.\n' + - '- commitment (●): someone promised to do something.\n' + - '- question (◆): a question directed at the user awaiting an answer.\n' + - '- decision (▲): a choice the group settled on.\n' + - '- artifact (✱): a document, link, or file referenced or to produce.\n' + - 'Extract only what the transcript supports; invent nothing. If there are no moments, return [].\n' + - 'Voice: specificity {{specificity}}/10, brevity {{brevity}}/10. {{voice.rules}}\n\n' + - 'Summary of the window: {{summary}}\n\n' + - 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nJSON array:', - [defaultEntitiesTemplate.id]: - 'You extract the named entities discussed in a meeting transcript — the people, artifacts, and topics that matter.\n' + - 'Return ONLY a JSON array of entities, no prose, no code fences.\n' + - 'Each element: {"name": string, "kind": one of "person"|"artifact"|"topic", "aliases": string[] (optional other names for the same thing)}.\n' + - '- person: a human named or clearly referred to.\n' + - '- artifact (✱): a document, file, link, system, or deliverable.\n' + - '- topic: a subject, project, or theme under discussion.\n' + - 'Extract only entities the transcript supports; invent nothing. Merge obvious aliases of one thing into a single entity. If there are none, return [].\n' + - 'Voice: specificity {{specificity}}/10, brevity {{brevity}}/10. {{voice.rules}}\n\n' + - 'Summary of the window: {{summary}}\n\n' + - 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nJSON array of entities:', -} - /** * The shipped fast-field prompt bundle (#61) — three small, specialized prompt DOCUMENTS, each bound to * a surface field via `field`. They are the composition units of the fan-out substrate: on newly @@ -290,9 +261,11 @@ export const defaultRollingSummaryTemplate: PromptTemplate = { description: 'hierarchical summary (#177): a rolling window over the existing distillates (+ packets as evidence)', summary: { level: 'rolling', windowMs: 60_000, maxChildren: 6, maxEvidence: 3, cadenceMs: 60_000 }, body: - 'You are writing a short rolling summary of a work session from the window summaries below. ' + - 'Summarize only what they support; invent nothing. One or two tight sentences.\n\n' + - 'Window summaries ({{windowStart}} -> {{windowEnd}}):\n{{children}}\n\nRolling summary:', + 'Keep the running notes for this stretch of a work session, from the window notes below.\n' + + '- Lead with the substance; the fewest words that carry it. One or two tight lines.\n' + + '- Never narrate the notes ("the notes indicate", "it was mentioned") — write what happened.\n' + + '- Keep only what the notes below support; invent nothing.\n\n' + + 'Window notes ({{windowStart}} → {{windowEnd}}):\n{{children}}\n\nRunning notes:', } export const defaultFiveMinuteSummaryTemplate: PromptTemplate = { @@ -304,10 +277,12 @@ export const defaultFiveMinuteSummaryTemplate: PromptTemplate = { description: 'hierarchical summary (#177): the concise five-minute view, over the window\'s rolling summaries plus a bounded selection of moments', summary: { level: 'five-minute', windowMs: 300_000, childLevel: 'rolling', maxChildren: 5, maxEvidence: 5, cadenceMs: 300_000 }, body: - 'You are writing a concise five-minute view of a work session from the lower-level summaries below. ' + - 'Summarize only what they support; invent nothing. Keep it tight.\n\n' + - 'Lower-level summaries (window {{windowStart}} -> {{windowEnd}}):\n{{children}}\n\n' + - 'Corroborating moments:\n{{evidence}}\n\nFive-minute summary:', + 'Write the five-minute view of a work session from the lower-level notes below — the substance only.\n' + + '- Lead with what happened; the fewest words that carry it. Keep it tight.\n' + + '- Never narrate the notes ("the notes indicate", "it was mentioned") — just write it.\n' + + '- Keep only what the notes and moments below support; invent nothing.\n\n' + + 'Lower-level notes (window {{windowStart}} → {{windowEnd}}):\n{{children}}\n\n' + + 'Moments:\n{{evidence}}\n\nFive-minute view:', } export const defaultSessionSummaryTemplate: PromptTemplate = { @@ -319,10 +294,11 @@ export const defaultSessionSummaryTemplate: PromptTemplate = { description: 'hierarchical summary (#177): the durable end-of-session result, over the session\'s five-minute summaries plus a bounded selection of moments', summary: { level: 'session', windowMs: 300_000, childLevel: 'five-minute', maxChildren: 12, maxEvidence: 8 }, body: - 'You are writing the durable result of a whole work session from the five-minute summaries below. ' + - 'Summarize only what they support; invent nothing. Lead with the outcome, then the key points.\n\n' + - 'Five-minute summaries (session {{windowStart}} -> {{windowEnd}}):\n{{children}}\n\n' + - 'Corroborating moments:\n{{evidence}}\n\nSession summary:', + 'Write the wrap-up of a whole work session from the five-minute notes below.\n' + + '- Lead with the outcome, then the key points — the substance, not a narration of the notes.\n' + + '- Keep only what the notes and moments below support; invent nothing.\n\n' + + 'Five-minute notes (session {{windowStart}} → {{windowEnd}}):\n{{children}}\n\n' + + 'Moments:\n{{evidence}}\n\nWrap-up:', } /** @@ -341,10 +317,11 @@ export const defaultEpisodeSummaryTemplate: PromptTemplate = { description: 'hierarchical summary (#177): a coherent stretch of activity — a wider window over the rolling summaries', summary: { level: 'episode', windowMs: 180_000, childLevel: 'rolling', maxChildren: 8, maxEvidence: 3, cadenceMs: 180_000 }, body: - 'You are naming a coherent stretch of a work session from the rolling summaries below — what this ' + - 'episode was about. Summarize only what they support; invent nothing. One or two tight sentences.\n\n' + - 'Rolling summaries (window {{windowStart}} -> {{windowEnd}}):\n{{children}}\n\n' + - 'Corroborating moments:\n{{evidence}}\n\nEpisode summary:', + 'Name what this stretch of the session was about, from the rolling notes below — one or two tight lines.\n' + + '- Lead with the substance; no narration of the notes themselves, no preamble.\n' + + '- Keep only what the notes and moments below support; invent nothing.\n\n' + + 'Rolling notes (window {{windowStart}} → {{windowEnd}}):\n{{children}}\n\n' + + 'Moments:\n{{evidence}}\n\nWhat this stretch was about:', } /** @@ -363,10 +340,10 @@ export const defaultProjectSummaryTemplate: PromptTemplate = { description: 'hierarchical summary (#177): durable cross-session project continuity, over every session\'s session summary — a new session supersedes the prior revision, never overwriting it', summary: { level: 'project', windowMs: 300_000, childLevel: 'session', maxChildren: 20, maxEvidence: 0 }, body: - 'You are writing the durable, continuing summary of a PROJECT from its per-session summaries below — ' + - 'the through-line across sessions. Summarize only what they support; invent nothing. Lead with where ' + - 'the project stands now, then the durable threads.\n\n' + - 'Session summaries ({{windowStart}} -> {{windowEnd}}):\n{{children}}\n\nProject summary:', + 'Write where this project stands now, from its per-session notes below — the through-line across sessions.\n' + + '- Lead with the current state, then the durable threads — the substance, not a narration of the notes.\n' + + '- Keep only what the notes below support; invent nothing.\n\n' + + 'Session notes ({{windowStart}} → {{windowEnd}}):\n{{children}}\n\nWhere the project stands:', } /** The shipped summary prompt bundle, finest→coarsest (all five #177 levels — episode/project land in slice 2). */ @@ -378,6 +355,79 @@ export const defaultSummaryTemplates: readonly PromptTemplate[] = [ defaultProjectSummaryTemplate, ] +/** + * The PREVIOUS shipped bodies of the builtin templates — the prior generation of a body we still want an + * UNEDITED install to auto-upgrade FROM. The one-time builtin-body refresh (DistillDocuments.ensureDefaults + * → seedOrRefreshBuiltin) uses these to detect an unedited builtin on an existing install: seeds are + * seed-if-absent, so an upgrader keeps its old body forever otherwise. A stored builtin is treated as + * unedited — and refreshed to the current shipped body — ONLY when it is still at version 1 AND its body is + * byte-for-byte the previous body for its id. Any user edit bumps the version off 1 (LayoutStore.put) and/or + * diverges the body, so an edited document is NEVER clobbered. Keyed by template id. Declared AFTER every + * template it references so its computed keys read initialized consts (no temporal-dead-zone access). Keep in + * lockstep with the bodies above: a refresh compares against these, never against the current body. + * + * NB (#245): the summary-family entries are the #177 bodies and the distill entry is the #130 NEUTRAL body — + * the generation that shipped before this notes-voice rewrite. A pre-#130 install already refreshed off the + * voice-baked distill body to the neutral one (version 2), so the voice-baked body is no longer a live upgrade + * source; a refreshed-once install therefore sits at version 2 and — by the conservative version===1 guard — + * does not auto-upgrade further. A fresh-since-#130 (still-version-1) install, or a fresh install, lands the + * notes-voice bodies automatically. The extract/entities entries are unchanged (#130 pre-neutral bodies) — this + * slice does not touch those templates. + */ +export const PREVIOUS_BUILTIN_BODIES: Readonly> = { + [defaultDistillTemplate.id]: + 'You are distilling a live meeting into a tight, factual summary of what just happened.\n' + + 'Summarize only what the transcript supports. Do not invent commitments or names.\n\n' + + 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nSummary:', + [defaultExtractTemplate.id]: + 'You extract typed moments from a meeting transcript. Return ONLY a JSON array, no prose, no code fences.\n' + + 'Each element: {"kind": one of "commitment"|"question"|"decision"|"artifact", "text": string, ' + + '"speaker": string (optional), "confidence": number 0..1 (optional), "answered": boolean (only for kind "question")}.\n' + + '- commitment (●): someone promised to do something.\n' + + '- question (◆): a question directed at the user awaiting an answer.\n' + + '- decision (▲): a choice the group settled on.\n' + + '- artifact (✱): a document, link, or file referenced or to produce.\n' + + 'Extract only what the transcript supports; invent nothing. If there are no moments, return [].\n' + + 'Voice: specificity {{specificity}}/10, brevity {{brevity}}/10. {{voice.rules}}\n\n' + + 'Summary of the window: {{summary}}\n\n' + + 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nJSON array:', + [defaultEntitiesTemplate.id]: + 'You extract the named entities discussed in a meeting transcript — the people, artifacts, and topics that matter.\n' + + 'Return ONLY a JSON array of entities, no prose, no code fences.\n' + + 'Each element: {"name": string, "kind": one of "person"|"artifact"|"topic", "aliases": string[] (optional other names for the same thing)}.\n' + + '- person: a human named or clearly referred to.\n' + + '- artifact (✱): a document, file, link, system, or deliverable.\n' + + '- topic: a subject, project, or theme under discussion.\n' + + 'Extract only entities the transcript supports; invent nothing. Merge obvious aliases of one thing into a single entity. If there are none, return [].\n' + + 'Voice: specificity {{specificity}}/10, brevity {{brevity}}/10. {{voice.rules}}\n\n' + + 'Summary of the window: {{summary}}\n\n' + + 'Transcript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nJSON array of entities:', + [defaultRollingSummaryTemplate.id]: + 'You are writing a short rolling summary of a work session from the window summaries below. ' + + 'Summarize only what they support; invent nothing. One or two tight sentences.\n\n' + + 'Window summaries ({{windowStart}} -> {{windowEnd}}):\n{{children}}\n\nRolling summary:', + [defaultEpisodeSummaryTemplate.id]: + 'You are naming a coherent stretch of a work session from the rolling summaries below — what this ' + + 'episode was about. Summarize only what they support; invent nothing. One or two tight sentences.\n\n' + + 'Rolling summaries (window {{windowStart}} -> {{windowEnd}}):\n{{children}}\n\n' + + 'Corroborating moments:\n{{evidence}}\n\nEpisode summary:', + [defaultFiveMinuteSummaryTemplate.id]: + 'You are writing a concise five-minute view of a work session from the lower-level summaries below. ' + + 'Summarize only what they support; invent nothing. Keep it tight.\n\n' + + 'Lower-level summaries (window {{windowStart}} -> {{windowEnd}}):\n{{children}}\n\n' + + 'Corroborating moments:\n{{evidence}}\n\nFive-minute summary:', + [defaultSessionSummaryTemplate.id]: + 'You are writing the durable result of a whole work session from the five-minute summaries below. ' + + 'Summarize only what they support; invent nothing. Lead with the outcome, then the key points.\n\n' + + 'Five-minute summaries (session {{windowStart}} -> {{windowEnd}}):\n{{children}}\n\n' + + 'Corroborating moments:\n{{evidence}}\n\nSession summary:', + [defaultProjectSummaryTemplate.id]: + 'You are writing the durable, continuing summary of a PROJECT from its per-session summaries below — ' + + 'the through-line across sessions. Summarize only what they support; invent nothing. Lead with where ' + + 'the project stands now, then the durable threads.\n\n' + + 'Session summaries ({{windowStart}} -> {{windowEnd}}):\n{{children}}\n\nProject summary:', +} + /** * The default meeting mode — window config lives here (mode document owns merge windows, per * ARCHITECTURE §7). Mirrors shared/contracts/examples/mode.meeting.json; the distiller reads only diff --git a/apps/engine/src/distill/distiller.ts b/apps/engine/src/distill/distiller.ts index c2f08ab0..34062221 100644 --- a/apps/engine/src/distill/distiller.ts +++ b/apps/engine/src/distill/distiller.ts @@ -8,6 +8,7 @@ import type { PresetDocuments } from '../presets/index.js' import type { WorkspaceRegistry } from '../store/index.js' import { VoiceDocuments, compileVoiceVars, interpolateTemplate, resolveVoice } from '../voice/index.js' import { bucketIntoWindows } from './merge.js' +import { NOTHING_NOTEWORTHY } from './defaults.js' import { DistillDocuments } from './documents.js' import { extractMoments, type ExtractInput } from './moments.js' import { captureLaneLabel } from './transcribe.js' @@ -69,6 +70,20 @@ export interface DistillerDeps { const isText = (chunk: CaptureChunk): boolean => chunk.encoding === 'utf8' && chunk.source !== 'focus' && chunk.contentType !== 'application/json' +/** + * Silence over noise (#245) — the deterministic pre-gate: the minimum count of OBSERVED window material + * (chunk.data, never our machine-owned capture-lane labels — the fields.ts precedent) below which a window is + * too small to hold any substantive phrase, so it produces NO distillate (and no moments/entities) without + * ever spending an invoke. This floor is deliberately LOW — LOWER than the fast-field gates (topic 40 / + * entities 60 / work-items 80). Those fields are OPTIONAL derived views that skip when a specific slice lacks + * enough material to be worth deriving, so a high bar is harmless. The distill note is the PRIMARY record of + * what was said; suppressing a real short utterance ("We ship Thursday.", "agreed, ship it") would be data + * loss. So the deterministic layer only drops windows too small to carry even a two-word substantive phrase + * (stray ASR tokens, acknowledgements, garble) and delegates the harder "enough words, no real substance" + * judgment to the model's NOTHING_NOTEWORTHY sentinel below. 12 chars ≈ two short words. + */ +const DISTILL_MIN_CHARS = 12 + const groupBySession = (chunks: readonly CaptureChunk[]): Map => { const groups = new Map() for (const chunk of chunks) { @@ -210,6 +225,17 @@ export class Distiller { const windows = bucketIntoWindows(sessionChunks, mode.distill.mergeWindow) for (const window of windows) { const workspaceId = window.chunks[0]!.workspaceId + // #245 silence gate (pre-gate): a window whose OBSERVED material is below the meaningful floor carries + // nothing a human notetaker would jot — skip the whole window (no distillate, and therefore no moments + // or entities from filler). Count chunk.data only, never the capture-lane labels the transcript below + // prefixes (fields.ts precedent: relevance is about observed material, not our label vocabulary). This + // is a cheap deterministic guard before any invoke; a window that clears it but still holds nothing is + // caught by the model's NOTHING_NOTEWORTHY sentinel after the summary call. Skips are logged, not silent. + const observedChars = window.chunks.map((chunk) => chunk.data).join('\n').trim().length + if (observedChars < DISTILL_MIN_CHARS) { + this.log(`distill window ${window.start}→${window.end} skipped: ${observedChars} < ${DISTILL_MIN_CHARS} observed chars (silence gate)`) + continue + } // #116: ONE correlation id per window pass — the distillate, its moments, its entity mentions, and // a guard hold (if the window is suspended) all share it, so the audit trail joins them exactly. const spanId = this.newId() @@ -280,6 +306,19 @@ export class Distiller { throw err } + // #245 silence gate (model escape): the summary template is instructed to answer with the exact + // sentinel when the window — though it cleared the character floor — holds nothing worth a note. Drop + // the whole window (no distillate, no moments, no entities) when the trimmed response is EITHER the + // exact sentinel (case-sensitive, full-text — a sentinel embedded inside a real note does NOT count, + // so a genuine note that mentions the token is kept) OR empty: an empty/whitespace-only response is + // the most literal "nothing", and persisting it as an empty-text distillate would defeat the gate. + // Determinism is preserved: the drop is a pure function of the (replayable) model text. + const summaryText = result.text.trim() + if (summaryText === '' || summaryText === NOTHING_NOTEWORTHY) { + this.log(`distill window ${window.start}→${window.end} dropped: ${summaryText === '' ? 'empty response' : 'nothing noteworthy'}`) + continue + } + const distillate: Distillate = { id: this.newId(), sessionId, @@ -288,7 +327,7 @@ export class Distiller { windowEnd: window.end, sourceChunks: window.chunks.map((chunk) => chunk.id), spanId, - text: result.text.trim(), + text: summaryText, voice: { scope: resolved.scope, dials: resolved.dials, diff --git a/apps/engine/src/distill/documents.test.ts b/apps/engine/src/distill/documents.test.ts index 9b10d92e..113bfc97 100644 --- a/apps/engine/src/distill/documents.test.ts +++ b/apps/engine/src/distill/documents.test.ts @@ -7,7 +7,7 @@ import type { PromptTemplate } from '@openinfo/contracts' import { WorkspaceRegistry } from '../store/index.js' import { NEUTRAL_DIALS, compileVoiceVars, interpolateTemplate } from '../voice/index.js' import { DistillDocuments } from './documents.js' -import { PREVIOUS_BUILTIN_BODIES, defaultDistillTemplate, defaultEntitiesTemplate, defaultExtractTemplate } from './defaults.js' +import { NOTHING_NOTEWORTHY, PREVIOUS_BUILTIN_BODIES, defaultDistillTemplate, defaultEntitiesTemplate, defaultExtractTemplate, defaultSummaryTemplates } from './defaults.js' const TEMPLATE_KIND = 'prompt-template' @@ -41,7 +41,7 @@ test('a fresh install seeds the three neutral window templates (no baked voice v }) }) -test('the rendered default distill prompt for a fresh install contains no voice/persona vocabulary (re-bloat guard)', async () => { +test('the rendered default distill prompt for a fresh install carries no dial vocabulary and pins the notes-voice register (#245)', async () => { await withStore((store) => { const docs = new DistillDocuments(store) docs.ensureDefaults() @@ -54,11 +54,16 @@ test('the rendered default distill prompt for a fresh install contains no voice/ transcript: 'we shipped the thing', }) assert.doesNotMatch(rendered, VOICE_VOCAB) - // and it dropped materially vs the previous voice-baked body (the length guard against re-bloat) - assert.ok( - docs.template().body.length < PREVIOUS_BUILTIN_BODIES[defaultDistillTemplate.id]!.length - 100, - 'neutral distill body must be materially shorter than the old voice-baked body', - ) + // The #245 register is opinionated by DESIGN, not by re-bloated dials: it drops the old slop framing, + // it explicitly BANS the transcription-narration openers, and it carries the silence sentinel. + const body = docs.template().body + assert.doesNotMatch(body, /tight, factual summary of what just happened/, 'the old slop framing is gone') + assert.match(body, /the transcript indicates/i, 'the body names the banned narration framings (as prohibitions)') + assert.match(body, /the speaker (said|expressed|stated)/i, 'the body bans the speaker-narration framings') + assert.ok(body.includes(NOTHING_NOTEWORTHY), 'the body instructs the silence sentinel') + // Still bounded (a re-bloat guard without depending on a since-superseded prior body): a note-taking + // instruction is a handful of lines, never a persona essay. + assert.ok(body.length < 1400, 'the distill body stays a tight instruction, not a re-bloated essay') }) }) @@ -138,3 +143,59 @@ test('a builtin whose v1 body diverges from the previous shipped body is left un assert.equal(now.body.body, 'some other v1 body {{transcript}}') }) }) + +// #245 — the SUMMARY-family bodies (distill window notes + the five hierarchical levels) speak the human +// note-taking register: no transcription-narration framings, honesty preserved, and each hierarchical level +// still interpolates its bound placeholders. The banned framings appear in the bodies only as PROHIBITIONS. + +// The narration framings the notes-voice register forbids the model from OPENING with. They legitimately +// appear inside the template bodies as the ban instruction itself, so this is a value-level, not body-level, +// guard: it is asserted against RENDERED slop in the suppression/pipeline tests, and asserted PRESENT (as a +// prohibition) in the body tests below. +const NARRATION_FRAMINGS = /the (speaker|transcript) (said|expressed|stated|indicates|shows|mentions)|it was (mentioned|noted|recorded|discussed)|the notes indicate/i + +test('#245: every summary-family body drops the old slop framing and keeps the invent-nothing honesty rule', async () => { + const distillId = defaultDistillTemplate.id + const families = [defaultDistillTemplate, ...defaultSummaryTemplates] + for (const t of families) { + assert.doesNotMatch(t.body, VOICE_VOCAB, `${t.id} carries no dial vocabulary`) + assert.doesNotMatch(t.body, /(tight, factual summary of what just happened|You are writing a|You are naming|You are distilling)/, `${t.id} drops the old report-speak framing`) + assert.match(t.body, /invent nothing|no invented/i, `${t.id} keeps an invent-nothing honesty rule`) + // the leading instruction reads like a note-taking directive, never a minutes preamble + assert.match(t.body.split('\n')[0]!, /\b(jot|keep|write|name)\b/i, `${t.id} leads with a note-taking directive`) + // only the distill window template carries the silence sentinel (the distiller is the drop point); + // the hierarchical levels ride on suppressed distillates and are not sentinel-gated (#245 design). + if (t.id === distillId) { + assert.ok(t.body.includes(NOTHING_NOTEWORTHY), 'the distill body instructs the silence sentinel') + assert.match(t.body, NARRATION_FRAMINGS, 'the distill body names the banned narration framings as prohibitions') + } + } +}) + +test('#245: an UNEDITED summary builtin left at its #177 body auto-upgrades to the notes-voice body', async () => { + await withStore((store) => { + for (const t of defaultSummaryTemplates) { + store.layouts.put(TEMPLATE_KIND, t.id, { ...t, body: PREVIOUS_BUILTIN_BODIES[t.id]! }) + } + const docs = new DistillDocuments(store) + docs.ensureDefaults() + for (const t of defaultSummaryTemplates) { + const now = store.layouts.getLatest(TEMPLATE_KIND, t.id)! + assert.equal(now.version, 2, `${t.id} refreshed (version bumped once)`) + assert.equal(now.body.body, t.body, `${t.id} refreshed to the notes-voice body`) + } + }) +}) + +test('#245: a USER-EDITED summary builtin is never clobbered by the refresh', async () => { + await withStore((store) => { + const target = defaultSummaryTemplates[0]! // rolling + store.layouts.put(TEMPLATE_KIND, target.id, { ...target, body: PREVIOUS_BUILTIN_BODIES[target.id]! }) + store.layouts.put(TEMPLATE_KIND, target.id, { ...target, body: 'MY OWN SUMMARY PROMPT {{children}}' }) + const docs = new DistillDocuments(store) + docs.ensureDefaults() + const now = store.layouts.getLatest(TEMPLATE_KIND, target.id)! + assert.equal(now.version, 2, 'the user edit stands — no refresh put') + assert.equal(now.body.body, 'MY OWN SUMMARY PROMPT {{children}}') + }) +}) diff --git a/apps/engine/src/distill/documents.ts b/apps/engine/src/distill/documents.ts index 60eadf5c..9df4ddd6 100644 --- a/apps/engine/src/distill/documents.ts +++ b/apps/engine/src/distill/documents.ts @@ -93,13 +93,13 @@ export class DistillDocuments { if (!this.store.layouts.getLatest(TEMPLATE_KIND, defaultAskTemplate.id)) { this.store.layouts.put(TEMPLATE_KIND, defaultAskTemplate.id, defaultAskTemplate) } - // The hierarchical-summary prompt documents (#177) — one per live-loop level. Seed-if-absent like the - // fast/judge documents; each edits over the same GET/PUT /templates routes and is read fresh per pass, so - // a user's edit to a level's cadence/bound/body takes effect with no restart and is never clobbered. + // The hierarchical-summary prompt documents (#177) — one per live-loop level. Seed-if-absent, then the + // same one-time unedited-builtin refresh the window templates use (#245): the summary bodies moved to the + // human note-taking register, so an UNEDITED summary builtin left at its #177 body auto-upgrades while a + // user edit is never clobbered. Each edits over the same GET/PUT /templates routes and is read fresh per + // pass, so a user's edit to a level's cadence/bound/body still takes effect with no restart. for (const summaryTemplate of defaultSummaryTemplates) { - if (!this.store.layouts.getLatest(TEMPLATE_KIND, summaryTemplate.id)) { - this.store.layouts.put(TEMPLATE_KIND, summaryTemplate.id, summaryTemplate) - } + this.seedOrRefreshBuiltin(summaryTemplate) } if (!this.store.layouts.getLatest(MODE_KIND, defaultMeetingMode.id)) { this.store.layouts.put(MODE_KIND, defaultMeetingMode.id, defaultMeetingMode) diff --git a/apps/engine/src/distill/guard.test.ts b/apps/engine/src/distill/guard.test.ts index c355d9ba..fc90c564 100644 --- a/apps/engine/src/distill/guard.test.ts +++ b/apps/engine/src/distill/guard.test.ts @@ -125,7 +125,7 @@ test('guard OFF (guardEnabled false) skips the guard entirely — pre-#63 behavi return Promise.resolve({ text: 'summary', endpoint: 'loc', slot: 'llm' }) } const distiller = new Distiller({ store: deps.store, voice: deps.voice, docs: deps.docs, fabric: deps.fabric, guardDocs: deps.guardDocs, guardHolds: deps.guardHolds, guardEnabled: () => false, invoke }) - const produced = await distiller.distillChunks([speech(1, 'hello')]) + const produced = await distiller.distillChunks([speech(1, 'hello everyone, thanks for joining')]) assert.equal(produced.length, 1) assert.equal(sawGuardOpt, false, 'no guard option is threaded when the flag is off') } finally { diff --git a/apps/engine/src/distill/preset-injection.test.ts b/apps/engine/src/distill/preset-injection.test.ts index 45417cc2..f6452bc0 100644 --- a/apps/engine/src/distill/preset-injection.test.ts +++ b/apps/engine/src/distill/preset-injection.test.ts @@ -58,7 +58,7 @@ test('pill P2: an UNSET preset is byte-identical to today (regression guard)', a assert.equal(prompts.length, 1, 'one summary invoke') // Byte-identical to the pre-P2 prompt: it starts with the shipped distill instruction and carries no // prepended preset context. - assert.ok(prompts[0]!.startsWith('You are distilling a live meeting'), 'the base distill prompt, unmodified') + assert.ok(prompts[0]!.startsWith('Jot the notes a sharp colleague would take'), 'the base distill prompt, unmodified') assert.ok(!prompts[0]!.startsWith('Context:'), 'no preset context prepended') assert.equal(distillate!.provenance.presetId, undefined, 'no presetId stamped when none was active') } finally { @@ -84,7 +84,7 @@ test('pill P2: flipping the active preset changes the distill prompt AND stamps // summary — proof the selection actually reaches the prompt path). assert.notEqual(withPreset, baseline, 'the prompt changed when the preset was flipped') assert.ok(withPreset.startsWith(`${salesBody}\n\n`), 'the active preset body is prepended') - assert.ok(withPreset.includes('You are distilling a live meeting'), 'the base distill prompt is preserved beneath it') + assert.ok(withPreset.includes('Jot the notes a sharp colleague would take'), 'the base distill prompt is preserved beneath it') // The why-record honestly names the preset that shaped the summary. assert.equal(distillate!.provenance.presetId, 'preset-sales', 'provenance names the active preset') diff --git a/apps/engine/src/distill/suppression.test.ts b/apps/engine/src/distill/suppression.test.ts new file mode 100644 index 00000000..49e5827b --- /dev/null +++ b/apps/engine/src/distill/suppression.test.ts @@ -0,0 +1,208 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { test } from 'node:test' +import assert from 'node:assert/strict' +import type { CaptureChunk } from '@openinfo/contracts' +import { FabricDocuments } from '../fabric/index.js' +import { WorkspaceRegistry } from '../store/index.js' +import { VoiceDocuments } from '../voice/index.js' +import { Distiller, type LlmInvoke } from './distiller.js' +import { DistillDocuments } from './documents.js' +import { NOTHING_NOTEWORTHY } from './defaults.js' + +/** + * Silence over noise (#245): a window with nothing worth noting must persist NO distillate. Two layers are + * proven here against the real Distiller with an injected model: + * (a) the deterministic pre-gate — a window below the meaningful-character floor is dropped WITHOUT ever + * calling the model (cheap), so no distillate/moment/entity is produced. + * (b) the model sentinel — a window that clears the floor but comes back as the exact NOTHING_NOTEWORTHY + * token is dropped; a sentinel embedded INSIDE a real note is kept; a normal note is kept. + */ + +const WS = 'default' + +const speech = (sequence: number, data: string): CaptureChunk => ({ + id: `sp-${sequence}`, + sessionId: 'ses-s', + workspaceId: WS, + source: 'mic', + sequence, + capturedAt: new Date(Date.UTC(2026, 6, 17, 14, 0, sequence)).toISOString(), + contentType: 'text/plain', + encoding: 'utf8', + data, +}) + +interface Harness { + dir: string + store: WorkspaceRegistry + distiller: Distiller + invokeCount: () => number + /** swap the summary-pass response mid-test (e.g. one dropped window then one kept). */ + setResponse: (r: string) => void +} + +/** Build a Distiller whose model returns `response` for the summary pass (mutable via setResponse). */ +const setup = async (response: string): Promise => { + const dir = await mkdtemp(join(tmpdir(), 'openinfo-distill-suppress-')) + const store = new WorkspaceRegistry(dir) + const voice = new VoiceDocuments(store) + voice.ensureDefaults() + const docs = new DistillDocuments(store) + docs.ensureDefaults() + const fabric = new FabricDocuments(store) + let calls = 0 + let current = response + const invoke: LlmInvoke = (messages) => { + calls++ + // Extraction passes (strict-JSON grammars) must not choke this summary-focused harness: hand them an + // empty array; the summary pass gets the configured response. + const prompt = messages[0]!.content + const isExtraction = prompt.includes('JSON array') + return Promise.resolve({ text: isExtraction ? '[]' : current, slot: 'llm', endpoint: 'fake-local' }) + } + const distiller = new Distiller({ store, voice, docs, fabric, invoke }) + return { dir, store, distiller, invokeCount: () => calls, setResponse: (r: string) => { current = r } } +} + +const teardown = async (h: Harness): Promise => { + h.store.close() + await rm(h.dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }) +} + +test('#245 pre-gate: a sub-threshold window persists NO distillate and never calls the model', async () => { + const h = await setup('this should never be reached') + try { + // "um, yeah" trims to 8 chars < the 12-char floor. + const produced = await h.distiller.distillChunks([speech(1, 'um, yeah')]) + assert.equal(produced.length, 0, 'no distillate returned') + assert.deepEqual(h.store.listDistillates(WS), [], 'nothing persisted') + assert.equal(h.invokeCount(), 0, 'the model was never invoked (cheap deterministic gate)') + } finally { + await teardown(h) + } +}) + +test('#245 pre-gate: a real short utterance CLEARS the floor and produces a note (no false suppression)', async () => { + const h = await setup('Ship Thursday.') + try { + // "We ship Thursday." is a meaningful 17-char sentence — it must NOT be silenced by the floor. + const produced = await h.distiller.distillChunks([speech(1, 'We ship Thursday.')]) + assert.equal(produced.length, 1, 'a real short utterance still produces a note') + assert.equal(h.store.listDistillates(WS).length, 1) + } finally { + await teardown(h) + } +}) + +test('#245 sentinel: an exact NOTHING_NOTEWORTHY response drops the distillate', async () => { + const h = await setup(NOTHING_NOTEWORTHY) + try { + const produced = await h.distiller.distillChunks([speech(1, 'so, um, are we... is this the meeting or, uh')]) + assert.equal(h.invokeCount(), 1, 'the window cleared the floor, so the model was consulted') + assert.equal(produced.length, 0, 'the sentinel dropped the distillate') + assert.deepEqual(h.store.listDistillates(WS), [], 'nothing persisted on the sentinel') + } finally { + await teardown(h) + } +}) + +test('#245 sentinel: leading/trailing whitespace around the exact token still drops', async () => { + const h = await setup(`\n ${NOTHING_NOTEWORTHY} \n`) + try { + const produced = await h.distiller.distillChunks([speech(1, 'so, um, are we... is this the meeting or, uh')]) + assert.equal(produced.length, 0, 'a trimmed exact match drops') + assert.deepEqual(h.store.listDistillates(WS), []) + } finally { + await teardown(h) + } +}) + +test('#245 sentinel: the token embedded INSIDE a real note does NOT drop (only the whole trimmed response counts)', async () => { + const note = `We discussed ${NOTHING_NOTEWORTHY} as a placeholder token.` + const h = await setup(note) + try { + const produced = await h.distiller.distillChunks([speech(1, 'we talked about the placeholder token today')]) + assert.equal(produced.length, 1, 'an embedded sentinel is kept — it is a real note') + assert.equal(h.store.listDistillates(WS)[0]!.text, note) + } finally { + await teardown(h) + } +}) + +test('#245 sentinel: a normal note is persisted unchanged', async () => { + const h = await setup('Feedback to QA — due soon.') + try { + const produced = await h.distiller.distillChunks([speech(1, 'I need to provide feedback to QA in eighteen minutes')]) + assert.equal(produced.length, 1) + assert.equal(h.store.listDistillates(WS)[0]!.text, 'Feedback to QA — due soon.') + } finally { + await teardown(h) + } +}) + +test('#245: a dropped window produces no moments and no entities either (suppression is whole-window)', async () => { + const h = await setup(NOTHING_NOTEWORTHY) + try { + await h.distiller.distillChunks([speech(1, 'so, um, are we... is this the meeting or, uh')], { extractMoments: true, extractEntities: true }) + assert.deepEqual(h.store.listDistillates(WS), [], 'no distillate') + assert.deepEqual(h.store.listMoments(WS), [], 'no moments extracted from a dropped window') + assert.equal(h.invokeCount(), 1, 'only the summary pass ran; extraction was skipped once the window was dropped') + } finally { + await teardown(h) + } +}) + +test('#245 D2: a whitespace-only / empty model response is dropped (the most literal "nothing")', async () => { + const h = await setup(' \n\t ') + try { + const produced = await h.distiller.distillChunks([speech(1, 'so, um, are we... is this the meeting or, uh')]) + assert.equal(produced.length, 0, 'an empty/whitespace response never becomes an empty-text distillate') + assert.deepEqual(h.store.listDistillates(WS), []) + } finally { + await teardown(h) + } +}) + +test('#245 D4: sentinel strictness is deliberate — a trailing period or a lowercase variant is KEPT', async () => { + // Trailing punctuation: not the exact token, so it is a (short) real note and is kept. + const withPeriod = `${NOTHING_NOTEWORTHY}.` + const h1 = await setup(withPeriod) + try { + const produced = await h1.distiller.distillChunks([speech(1, 'we talked about the placeholder token today')]) + assert.equal(produced.length, 1, 'a trailing period is not the exact sentinel — kept') + assert.equal(h1.store.listDistillates(WS)[0]!.text, withPeriod) + } finally { + await teardown(h1) + } + // Lowercase: case-sensitive match, so a lowercased token is not the sentinel — kept. + const lower = NOTHING_NOTEWORTHY.toLowerCase() + const h2 = await setup(lower) + try { + const produced = await h2.distiller.distillChunks([speech(1, 'we talked about the placeholder token today')]) + assert.equal(produced.length, 1, 'a lowercase variant is not the exact sentinel — kept') + assert.equal(h2.store.listDistillates(WS)[0]!.text, lower) + } finally { + await teardown(h2) + } +}) + +test('#245 D4: a sentinel-dropped window does not poison the next — a following normal window persists', async () => { + const h = await setup(NOTHING_NOTEWORTHY) + try { + // Window 1: nothing worth noting → dropped. + const first = await h.distiller.distillChunks([speech(1, 'so, um, are we... is this the meeting or, uh')]) + assert.equal(first.length, 0, 'first window dropped') + assert.deepEqual(h.store.listDistillates(WS), [], 'nothing persisted yet') + // Window 2: real content → persisted normally, unaffected by the earlier drop. + h.setResponse('Ship date confirmed for Thursday.') + const second = await h.distiller.distillChunks([speech(2, 'okay so we are confirming the ship date for Thursday')]) + assert.equal(second.length, 1, 'second window persists normally') + const stored = h.store.listDistillates(WS) + assert.equal(stored.length, 1, 'exactly one distillate — only the second window') + assert.equal(stored[0]!.text, 'Ship date confirmed for Thursday.') + } finally { + await teardown(h) + } +}) diff --git a/shared/contracts/examples/promptTemplate.distill.json b/shared/contracts/examples/promptTemplate.distill.json index 1b11591b..cb8594a0 100644 --- a/shared/contracts/examples/promptTemplate.distill.json +++ b/shared/contracts/examples/promptTemplate.distill.json @@ -1,4 +1,4 @@ { "id": "tpl-distill-default", "name": "distill-default", "kind": "distill", "slot": "llm", "builtin": true, - "description": "rolling-merge summary; neutral factual default (no baked voice vector — dials remain available to edited templates)", - "body": "You are distilling a live meeting into a tight, factual summary of what just happened.\nSummarize only what the transcript supports. Do not invent commitments or names.\n\nTranscript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nSummary:" } + "description": "rolling-merge window notes; human note-taking register, silence when nothing was said (no baked voice vector — dials remain available to edited templates)", + "body": "Jot the notes a sharp colleague would take on this stretch of a live meeting — the substance, nothing more.\n- Lead with the fact itself. Write \"Feedback to QA — due soon\", not \"The speaker expressed a goal to provide feedback\".\n- Never narrate the transcript. Do not open with \"the speaker said/expressed/stated\", \"the transcript indicates/shows\", or \"it was mentioned/noted/recorded/discussed\" — write the thing, not the fact that it was said.\n- Keep only what the transcript supports: no invented commitments, names, numbers, or motives.\n- Terse: the fewest words that carry it. No preamble, no framing, no sign-off.\n- If nothing here is worth a note — only filler, fragments, or garble — reply with exactly NOTHING_NOTEWORTHY and nothing else.\n\nTranscript (merge window {{windowStart}} → {{windowEnd}}):\n{{transcript}}\n\nNotes:" } diff --git a/shared/contracts/examples/promptTemplate.summary.json b/shared/contracts/examples/promptTemplate.summary.json index 8a940eb1..6d4286de 100644 --- a/shared/contracts/examples/promptTemplate.summary.json +++ b/shared/contracts/examples/promptTemplate.summary.json @@ -13,5 +13,5 @@ "maxEvidence": 5, "cadenceMs": 300000 }, - "body": "You are writing a concise five-minute view of a work session from the lower-level summaries below. Summarize only what they support; invent nothing. Keep it tight.\n\nLower-level summaries (window {{windowStart}} -> {{windowEnd}}):\n{{children}}\n\nCorroborating moments:\n{{evidence}}\n\nFive-minute summary:" + "body": "Write the five-minute view of a work session from the lower-level notes below — the substance only.\n- Lead with what happened; the fewest words that carry it. Keep it tight.\n- Never narrate the notes (\"the notes indicate\", \"it was mentioned\") — just write it.\n- Keep only what the notes and moments below support; invent nothing.\n\nLower-level notes (window {{windowStart}} → {{windowEnd}}):\n{{children}}\n\nMoments:\n{{evidence}}\n\nFive-minute view:" }