From 4bd3fcf93fc9f42d1a93d5f595d36f16ee2da06e Mon Sep 17 00:00:00 2001 From: Marcelo Ceccon <32395187+marceloceccon@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:05:13 +0000 Subject: [PATCH] fix(parser): extractConfidence reads the last CONFIDENCE marker with digits The protocol puts the score on the final line, but extractConfidence took the first "confidence:" hit: an earlier preview captured the score, and an inline "Confidence: high" made the whole response score 50 even with a valid trailing CONFIDENCE line. It now returns the last marker followed by digits (Roundtable's semantics); markers without digits are skipped. Default 50 and clamping are unchanged. This changes ConsensusEngine.run() scores for responses that mention "confidence:" before their trailing line. The existing test that pinned first-occurrence (with a comment misstating Roundtable's parser) is inverted; new parser and engine-level tests cover the trailing rule. extractTrailingConfidence (added in the unreleased 0.13.0, already used by Roundtable's main) stays as a deprecated alias of extractConfidence, so the order in which the repos land or release does not matter. --- CHANGELOG.md | 10 +++- README.md | 6 +- src/__tests__/claims-and-budget.test.ts | 26 +++++---- src/__tests__/engine.test.ts | 20 +++++++ src/__tests__/parser.test.ts | 15 +++-- src/index.ts | 1 + src/parser.ts | 75 ++++++++++--------------- 7 files changed, 88 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d759f9..80ba745 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,11 +22,17 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), [SemVer](https - `extractClaims`, `parseClaimsJSON`, `buildClaimExtractorUserPrompt`, `CLAIM_EXTRACTOR_SYSTEM_PROMPT`, and the `ClaimContradiction` / `ClaimDigest` types (prompt, parser and fuzzy quote check unchanged) - `CostCapExceededError`, `assertWithinCostCap` and the `CostCap` type -- `extractTrailingConfidence`: last `CONFIDENCE: N` marker followed by digits (Roundtable's parsing semantics) +- `extractTrailingConfidence`: deprecated alias of `extractConfidence` (same semantics, see below), kept for callers written against the pre-release + +### Changed — `extractConfidence` reads the trailing marker + +`extractConfidence` now returns the value of the **last** `confidence:` marker followed by digits, instead of the first marker. A marker without digits (e.g. "Confidence: high") is skipped rather than returning 50. The protocol asks for the score on the final line; before, an inline mention or a previewed score earlier in a response captured it, and "Confidence: high … CONFIDENCE: 80" scored 50. These are the semantics Roundtable always used. + +This changes `ConsensusEngine.run()` scores for responses that mention "confidence:" before their trailing line; responses with a single trailing marker score exactly as before. The default (50 when no marker has digits) and clamping are unchanged. ### Backward compatibility -Additive only. Every 0.12 export is still exported with identical runtime source, and the `.d.ts` files for the engine, prompts, stats, events and personas are byte-identical; `types.d.ts`, `parser.d.ts` and `index.d.ts` only gain declarations. `ConsensusEngine.run()`, `extractConfidence` and every existing type are unchanged. No new runtime dependencies. Tests: 145 existing (unmodified) + 113 new = 258. +Apart from the `extractConfidence` change above, additive only. Every other 0.12 export keeps identical runtime source, and the `.d.ts` files for the engine, prompts, stats, events and personas are byte-identical; `types.d.ts`, `parser.d.ts` and `index.d.ts` only gain declarations or doc text. No existing signature or type changed. No new runtime dependencies. Tests: 145 existing (one inverted for the parser change) + 116 new = 261. ## [0.12.0] — 2026-11-14 diff --git a/README.md b/README.md index 38ad1f8..7d97e76 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,7 @@ console.log(result.synthesis?.majorityPosition); - **Round 1 is blind by default.** Participants run in parallel, see no one else. Flip `blindFirstRound: false` to go sequential (rare — mostly for deterministic replay). - **Rounds 2+ are sequential.** Speaking order is randomized unless `randomizeOrder: false`. Each speaker sees everyone who came before them — including earlier speakers in the current round. -- **Every response must end with `CONFIDENCE: N`** where N is an integer 0–100. Missing marker → 50 (neutral). +- **Every response must end with `CONFIDENCE: N`** where N is an integer 0–100. If several markers appear, the last one with a number wins (an inline "Confidence: high" is ignored). Missing marker → 50 (neutral). - **Consensus score** = `round(clamp(μ − 0.5·σ, 0, 100))` using population stddev. - **Disagreement detected** when two participants' confidences differ by ≥ 20 (tunable). - **Early stop** when `|score_k − score_{k−1}| ≤ 3` (tunable). Only checked from round 2 onward. @@ -504,7 +504,7 @@ digest.contradictions; // [{ claim, sides: [{ stance, participantIds, quote }] } assertWithinCostCap(runningCostUSD, capUSD); // throws CostCapExceededError above the cap ``` -`extractClaims` makes one call and soft-fails (an error or unparseable output yields an empty digest with `error` set); aborts propagate. `extractTrailingConfidence` parses the last `CONFIDENCE: N` marker followed by digits, for hosts that want trailing-line semantics; `extractConfidence` and `ConsensusEngine.run()` are unchanged. +`extractClaims` makes one call and soft-fails (an error or unparseable output yields an empty digest with `error` set); aborts propagate. ## Types @@ -550,7 +550,7 @@ ParticipantSchema.parse(untrustedInput); git clone https://github.com/entropyvortex/ai-consensus-core.git cd ai-consensus-core npm install -npm run test # 258 tests, vitest +npm run test # 261 tests, vitest npm run test:coverage npm run build # emits ESM + .d.ts into dist/ ``` diff --git a/src/__tests__/claims-and-budget.test.ts b/src/__tests__/claims-and-budget.test.ts index 81baeb0..83c1d99 100644 --- a/src/__tests__/claims-and-budget.test.ts +++ b/src/__tests__/claims-and-budget.test.ts @@ -159,25 +159,29 @@ describe("extractClaims — contract: one call, soft-fail, quotes checked agains }); }); -describe("extractTrailingConfidence — contract: last marker followed by digits", () => { +describe("extractConfidence — contract: last marker followed by digits (Roundtable parity)", () => { it("picks the trailing marker over an earlier preview", () => { - expect(extractTrailingConfidence("I had CONFIDENCE: 30 earlier but after reviewing\n\nCONFIDENCE: 88")).toBe(88); + expect(extractConfidence("I had CONFIDENCE: 30 earlier but after reviewing\n\nCONFIDENCE: 88")).toBe(88); }); - it("ignores markers without digits, unlike extractConfidence", () => { - const text = "Confidence: high in the approach.\n\nCONFIDENCE: 72"; - expect(extractTrailingConfidence(text)).toBe(72); - expect(extractConfidence(text)).toBe(50); // existing first-marker behaviour is unchanged + it("ignores markers without digits", () => { + expect(extractConfidence("Confidence: high in the approach.\n\nCONFIDENCE: 72")).toBe(72); }); it("clamps, defaults to 50, and is case-insensitive", () => { - expect(extractTrailingConfidence("no marker here")).toBe(50); - expect(extractTrailingConfidence("CONFIDENCE: 150")).toBe(100); - expect(extractTrailingConfidence("confidence:\n 9")).toBe(9); - expect(extractTrailingConfidence("JUDGE_CONFIDENCE: 61")).toBe(61); - expect(extractTrailingConfidence("CONFIDENCE: none")).toBe(50); + expect(extractConfidence("no marker here")).toBe(50); + expect(extractConfidence("CONFIDENCE: 150")).toBe(100); + expect(extractConfidence("confidence:\n 9")).toBe(9); + expect(extractConfidence("JUDGE_CONFIDENCE: 61")).toBe(61); + expect(extractConfidence("CONFIDENCE: none")).toBe(50); }); }); +describe("extractTrailingConfidence — deprecated alias", () => { + it("is extractConfidence", () => { + expect(extractTrailingConfidence).toBe(extractConfidence); + }); +}); + describe("cost cap — contract: throw only when strictly above a positive cap", () => { it("formats the error like Roundtable did", () => { diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts index 825ccb5..066fac6 100644 --- a/src/__tests__/engine.test.ts +++ b/src/__tests__/engine.test.ts @@ -988,3 +988,23 @@ describe("ConsensusEngine — deterministic replay", () => { expect(unique.size).toBeGreaterThan(1); }); }); + +// ───────────────────────────────────────────────────────────── +// Confidence parsing in run() (0.13: last marker wins) +// ───────────────────────────────────────────────────────────── + +describe("ConsensusEngine — confidence comes from the trailing marker", () => { + it("ignores an earlier inline 'Confidence:' mention and an earlier preview", async () => { + const caller: ModelCaller = async (req) => ({ + content: + req.participantId === "p1" + ? "Confidence: high that this is right.\nMore reasoning.\nCONFIDENCE: 82" + : "I would say CONFIDENCE: 40 at first, but on reflection\nCONFIDENCE: 64", + }); + const result = await new ConsensusEngine(caller).run( + baseOptions({ participants: [P("p1", 0), P("p2", 1)], maxRounds: 1 }), + ); + const byId = Object.fromEntries(result.rounds[0]!.responses.map((r) => [r.participantId, r.confidence])); + expect(byId).toEqual({ p1: 82, p2: 64 }); + }); +}); diff --git a/src/__tests__/parser.test.ts b/src/__tests__/parser.test.ts index ace79d8..273de65 100644 --- a/src/__tests__/parser.test.ts +++ b/src/__tests__/parser.test.ts @@ -31,11 +31,16 @@ describe("extractConfidence", () => { expect(extractConfidence("CoNfIdEnCe: 75")).toBe(75); }); - it("matches the first occurrence when several are present", () => { - // The roundtable reference uses a non-global regex, so the first match - // wins. We preserve that ordering — later confidences are treated as - // commentary, not overrides. - expect(extractConfidence("CONFIDENCE: 30\nmore\nCONFIDENCE: 90")).toBe(30); + it("takes the last marker when several are present (since 0.13)", () => { + // The protocol puts the score on the final line; an earlier preview or + // an inline mention must not capture it. Matches Roundtable's + // last-match parser. + expect(extractConfidence("CONFIDENCE: 30\nmore\nCONFIDENCE: 90")).toBe(90); + }); + + it("skips markers without digits instead of returning 50 (since 0.13)", () => { + expect(extractConfidence("Confidence: high in the approach.\n\nCONFIDENCE: 72")).toBe(72); + expect(extractConfidence("CONFIDENCE: 72\nconfidence: unclear")).toBe(72); }); it("clamps values above 100", () => { diff --git a/src/index.ts b/src/index.ts index 78eee5a..c7311e5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,6 +26,7 @@ export { stripConfidenceLine, } from "./parser.js"; +/** @deprecated Use extractConfidence (same semantics since 0.13). */ export { extractTrailingConfidence } from "./parser.js"; export { diff --git a/src/parser.ts b/src/parser.ts index 9637513..2d884fc 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -16,35 +16,48 @@ function isDigit(ch: string): boolean { } /** - * Extract the trailing `CONFIDENCE: N` value. Clamps to [0, 100] and - * defaults to 50 when the marker is absent or the following value is - * malformed. + * Extract the trailing `CONFIDENCE: N` value: the LAST `confidence:` marker + * (case-insensitive) that is followed by digits. Clamps to [0, 100] and + * defaults to 50 when no such marker exists. + * + * The protocol asks for the score on the final line, so earlier inline + * mentions such as "Confidence: high" or a previewed score cannot capture + * the value. (Before 0.13 the first marker won, and a first marker without + * digits returned 50 even when a valid trailing line followed.) Same + * semantics as Roundtable's `/CONFIDENCE:\s*(\d+)/gi` last-match parser; + * `JUDGE_CONFIDENCE: N` also matches, as it always did. * * The default is intentional: an absent marker is a model compliance * issue, not a "low-confidence" signal, so we treat it as neutral rather * than letting it skew the consensus score downward. * - * Implemented with linear-time string parsing (no regex, no ReDoS). A - * prefix with no digits after it yields `parseInt("")` → NaN, which - * `clampConfidence` collapses to the 50 default — the single invalid- - * input path. + * Implemented as a linear-time string scan (no regex over the whole text, + * no ReDoS). */ export function extractConfidence(text: string): number { const lower = text.toLowerCase(); const prefix = "confidence:"; - const idx = lower.indexOf(prefix); - if (idx === -1) return 50; - - let i = idx + prefix.length; - while (i < text.length && isWhitespace(text[i]!)) i++; - - const start = i; - while (i < text.length && isDigit(text[i]!)) i++; - - const n = Number.parseInt(text.slice(start, i), 10); - return clampConfidence(n); + let last: number | undefined; + let idx = lower.indexOf(prefix); + while (idx !== -1) { + let i = idx + prefix.length; + while (i < text.length && /\s/.test(text[i]!)) i++; + const start = i; + while (i < text.length && isDigit(text[i]!)) i++; + if (i > start) last = Number.parseInt(text.slice(start, i), 10); + idx = lower.indexOf(prefix, idx + prefix.length); + } + return last === undefined ? 50 : clampConfidence(last); } +/** + * Alias of {@link extractConfidence}, which has these semantics since 0.13. + * Kept so callers written against the 0.13 pre-release keep working. + * + * @deprecated Use {@link extractConfidence}. + */ +export const extractTrailingConfidence: (text: string) => number = extractConfidence; + /** * Extract the judge's self-reported synthesis confidence. Tolerates both * `JUDGE_CONFIDENCE: 87` and `JUDGE_CONFIDENCE: [87]` forms, since the @@ -97,29 +110,3 @@ export function stripConfidenceLine(text: string): string { return text.replace(/\nCONFIDENCE:\s*\d+\s*$/i, "").trim(); } -/** - * Extract the LAST `CONFIDENCE: N` marker that is followed by digits. - * Clamps to [0, 100]; defaults to 50 when no such marker exists. - * - * Unlike {@link extractConfidence} (first marker, any value), earlier - * inline mentions such as "Confidence: high" or a previewed score cannot - * capture the value: the trailing line the protocol asks for wins. Same - * semantics as Roundtable's `/CONFIDENCE:\s*(\d+)/gi` last-match parser - * (case-insensitive, so `JUDGE_CONFIDENCE: N` also matches), implemented - * as a linear scan. - */ -export function extractTrailingConfidence(text: string): number { - const lower = text.toLowerCase(); - const prefix = "confidence:"; - let last: number | undefined; - let idx = lower.indexOf(prefix); - while (idx !== -1) { - let i = idx + prefix.length; - while (i < text.length && /\s/.test(text[i]!)) i++; - const start = i; - while (i < text.length && isDigit(text[i]!)) i++; - if (i > start) last = Number.parseInt(text.slice(start, i), 10); - idx = lower.indexOf(prefix, idx + prefix.length); - } - return last === undefined ? 50 : clampConfidence(last); -}