Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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/
```
Expand Down
26 changes: 15 additions & 11 deletions src/__tests__/claims-and-budget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
20 changes: 20 additions & 0 deletions src/__tests__/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
});
});
15 changes: 10 additions & 5 deletions src/__tests__/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export {
stripConfidenceLine,
} from "./parser.js";

/** @deprecated Use extractConfidence (same semantics since 0.13). */
export { extractTrailingConfidence } from "./parser.js";

export {
Expand Down
75 changes: 31 additions & 44 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
Loading