/** * v1.4.22 — Coach evidence-block (`---KEYVALUES---` … `---END---`) * parser. * * The Coach prompt instructs the model to append, after its prose * reply, a sentinel block carrying the load-bearing numbers it cited: * * ---KEYVALUES--- * avg30 systolic: 138 [mmHg] (last30days) * Tue 6 May: 142/88 [mmHg] * ---END--- * * This module strips that block out of the streamed prose and parses * each line into a `CoachKeyValue`. The result feeds the * `provenance.keyValues` field that the UI renders as a collapsible * disclosure. * * Defence-in-depth: * - Hard cap 1 KB on the sentinel block (prompt-injection guard). * - Hard cap 8 lines kept (per the prompt contract). * - Each line is validated against `coachKeyValueSchema`; malformed * lines surface in `parsed.malformed[]` with a typed reason * (v1.4.23 H1 — replaced the silent-drop path). * - When the sentinel pair is malformed (e.g. no closing `---END---`, * unbalanced sentinels), the parser still returns whatever rows it * could parse plus a malformed flag; the caller logs * `coach.keyvalues.parse_failed` (full block invalid) or * `coach.keyvalues.parse_partial` (mixed valid + invalid) for ops * visibility. */ import { coachKeyValueSchema, type CoachKeyValue } from "./types"; /** Sentinel block payload hard cap — 1 KB after the opening marker. */ const SENTINEL_BYTE_CAP = 1024; /** Max key/value rows kept inside the block (prompt-contract value). */ const SENTINEL_LINE_CAP = 8; /** Per-line value cap before we reject the row (defence-in-depth). */ const VALUE_BYTE_CAP = 200; /** Per-line label cap mirroring the prompt-contract value of 40 chars. */ const LABEL_BYTE_CAP = 80; const OPEN_SENTINEL = "---KEYVALUES---"; const CLOSE_SENTINEL = "---END---"; /** * Why a candidate row failed to parse. Surfaces to the caller via * `SentinelParseResult.malformed[]` so ops dashboards can attribute * partial failures (mixed valid + invalid rows) without the silent * drops the v1.4.22 W3 implementation paid. * * - `missing_colon` — line had no `:` separator. * - `value_overflow` — value exceeded `VALUE_BYTE_CAP`. * - `label_overflow` — label exceeded `LABEL_BYTE_CAP`. * - `no_END_marker` — the closing `---END---` was missing. * - `byte_overflow` — block exceeded `SENTINEL_BYTE_CAP`. * - `schema_invalid` — row passed shape but Zod rejected it * (e.g. empty value after stripping). */ export type SentinelMalformedReason = | "missing_colon" | "value_overflow" | "label_overflow" | "no_END_marker" | "byte_overflow" | "schema_invalid"; export interface SentinelMalformedEntry { rawLine: string; reason: SentinelMalformedReason; } /** * Result of parsing one body line. Either returns the `CoachKeyValue` * shape or a typed reason the line failed (so the caller can surface * partial-failure observability in the wide-event annotation). */ export type LineParseOutcome = | { ok: true; value: CoachKeyValue } | { ok: false; reason: SentinelMalformedReason }; /** * Parse one body line of the form * `