Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | 20x 16x 5x 5x 8x 8x 8x 8x 8x 8x 8x 8x 8x 188x 185x 44x 32x 19x 36x 36x 36x 36x 36x 36x 36x 36x 6x 6x 6x 6x 10x 6x 6x 6x 6x 6x 6x 6x 9x 9x 9x 1x 8x 10x 10x 10x 10x 10x 8x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module Utils/SignificanceScoring
* @description 5-dimension composite significance scoring engine for EP events.
*
* Scores each event across five dimensions (0–10 each) and computes a weighted
* composite score used for publication prioritisation decisions:
*
* | Dimension | Weight |
* |----------------------------|--------|
* | Parliamentary Significance | 0.25 |
* | Policy Impact | 0.25 |
* | Public Interest | 0.20 |
* | Temporal Urgency | 0.15 |
* | Institutional Relevance | 0.15 |
*
* Decision thresholds follow the analysis template:
*
* | Composite | Decision |
* |-----------|----------|
* | 0.0 – 3.9 | skip |
* | 4.0 – 5.9 | hold |
* | ≥ 6.0 | publish |
*
* @see analysis/templates/significance-scoring.md
*/
import type {
SignificanceScore,
SignificanceScoringInput,
SignificanceBatchResult,
PublicationDecision,
} from '../types/significance.js';
// ─── Markdown sanitization ────────────────────────────────────────────────────
/**
* Sanitize untrusted text for safe use in a Markdown table cell.
*
* Escapes pipe characters, backslashes, and HTML entities, then normalizes
* whitespace to prevent table layout corruption from external EP data.
*
* @param input - Untrusted cell text
* @returns Sanitized text safe for Markdown table cells
*/
function sanitizeMdCell(input: string): string {
return input
.replace(/\\/gu, '\\\\')
.replace(/\|/gu, '\\|')
.replace(/&/gu, '&')
.replace(/</gu, '<')
.replace(/>/gu, '>')
.replace(/[\r\n]+/gu, ' ')
.trim();
}
/**
* Normalize a reference string: treat empty / whitespace-only values as
* missing so that the table cell shows a placeholder instead of blank.
*
* @param ref - Optional reference string
* @returns The trimmed reference, or undefined if empty/missing
*/
function normalizeRef(ref: string | undefined): string | undefined {
if (!ref) return undefined;
const trimmed = ref.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
// ─── Scoring constants ────────────────────────────────────────────────────────
/** Weight applied to Parliamentary Significance dimension */
export const WEIGHT_PARLIAMENTARY = 0.25;
/** Weight applied to Policy Impact dimension */
export const WEIGHT_POLICY = 0.25;
/** Weight applied to Public Interest dimension */
export const WEIGHT_PUBLIC_INTEREST = 0.2;
/** Weight applied to Temporal Urgency dimension */
export const WEIGHT_URGENCY = 0.15;
/** Weight applied to Institutional / Cross-Group Relevance dimension */
export const WEIGHT_INSTITUTIONAL = 0.15;
/** Minimum score floor (dimension and composite) */
const SCORE_MIN = 0;
/** Maximum score ceiling (dimension and composite) */
const SCORE_MAX = 10;
/** Composite score at or above which the decision is "publish" */
export const THRESHOLD_PUBLISH = 6.0;
/** Composite score at or above which the decision is "hold" (below publish) */
export const THRESHOLD_HOLD = 4.0;
// ─── Helpers ──────────────────────────────────────────────────────────────────
/**
* Clamp a numeric value to the 0–10 scoring range.
*
* @param value - Raw numeric input
* @returns Value clamped to [0, 10]
*/
export function clampScore(value: number): number {
if (!Number.isFinite(value)) return SCORE_MIN;
return Math.min(SCORE_MAX, Math.max(SCORE_MIN, value));
}
/**
* Derive a publication decision from a composite score.
*
* @param composite - Weighted composite score (0–10)
* @returns Publication decision
*/
export function deriveDecision(composite: number): PublicationDecision {
if (composite >= THRESHOLD_PUBLISH) return 'publish';
if (composite >= THRESHOLD_HOLD) return 'hold';
return 'skip';
}
// ─── Core scoring ─────────────────────────────────────────────────────────────
/**
* Compute a composite significance score for a single event.
*
* All dimension values are clamped to [0, 10]. The composite is the
* weighted average using the standard template weights.
*
* @param input - Dimension scores for one event
* @returns Significance score with composite and publication decision
*/
export function scoreSignificance(input: SignificanceScoringInput): SignificanceScore {
const parliamentarySignificance = clampScore(input.parliamentarySignificance);
const policyImpact = clampScore(input.policyImpact);
const publicInterest = clampScore(input.publicInterest);
const temporalUrgency = clampScore(input.temporalUrgency);
const institutionalRelevance = clampScore(input.institutionalRelevance);
const composite =
parliamentarySignificance * WEIGHT_PARLIAMENTARY +
policyImpact * WEIGHT_POLICY +
publicInterest * WEIGHT_PUBLIC_INTEREST +
temporalUrgency * WEIGHT_URGENCY +
institutionalRelevance * WEIGHT_INSTITUTIONAL;
const roundedComposite = Math.round(composite * 100) / 100;
return {
parliamentarySignificance,
policyImpact,
publicInterest,
temporalUrgency,
institutionalRelevance,
composite: roundedComposite,
decision: deriveDecision(roundedComposite),
};
}
/**
* Score a batch of events and return ranked results with a summary.
*
* Events are scored individually then sorted by composite score descending.
*
* @param inputs - Array of event scoring inputs
* @returns Batch result with ranked scores and decision summary counts
*/
export function scoreBatch(inputs: readonly SignificanceScoringInput[]): SignificanceBatchResult {
const scores = inputs.map(scoreSignificance);
// Sort by composite descending (stable sort preserves input order for ties)
const ranked = [...scores].sort((a, b) => b.composite - a.composite);
const summary = { publish: 0, hold: 0, skip: 0 };
for (const s of ranked) {
summary[s.decision]++;
}
return { scores: ranked, summary };
}
/**
* Generate a markdown report for a single significance score.
*
* Produces a table matching the template format with dimension breakdown,
* composite calculation, and publication decision.
*
* @param score - Computed significance score
* @param title - Event title
* @param reference - Optional EP reference identifier
* @returns Markdown string
*/
export function formatScoreMarkdown(
score: SignificanceScore,
title: string,
reference?: string
): string {
const safeTitle = sanitizeMdCell(title);
const safeRef = normalizeRef(reference);
const refLine = safeRef ? `| **EP Reference** | \`${sanitizeMdCell(safeRef)}\` |\n` : '';
const decisionEmoji =
score.decision === 'publish' ? '📰' : score.decision === 'hold' ? '📋' : '🗄️';
const decisionLabel =
score.decision === 'publish' ? 'Publish' : score.decision === 'hold' ? 'Hold' : 'Skip';
return `### ${safeTitle}
| Field | Value |
|-------|-------|
| **Event** | ${safeTitle} |
${refLine}
| Dimension | Raw Score | Weight | Weighted Score |
|-----------|:---------:|:------:|:--------------:|
| Parliamentary Significance | ${score.parliamentarySignificance.toFixed(1)} | ${WEIGHT_PARLIAMENTARY} | ${(score.parliamentarySignificance * WEIGHT_PARLIAMENTARY).toFixed(2)} |
| Policy Impact | ${score.policyImpact.toFixed(1)} | ${WEIGHT_POLICY} | ${(score.policyImpact * WEIGHT_POLICY).toFixed(2)} |
| Public Interest | ${score.publicInterest.toFixed(1)} | ${WEIGHT_PUBLIC_INTEREST} | ${(score.publicInterest * WEIGHT_PUBLIC_INTEREST).toFixed(2)} |
| Temporal Urgency | ${score.temporalUrgency.toFixed(1)} | ${WEIGHT_URGENCY} | ${(score.temporalUrgency * WEIGHT_URGENCY).toFixed(2)} |
| Institutional Relevance | ${score.institutionalRelevance.toFixed(1)} | ${WEIGHT_INSTITUTIONAL} | ${(score.institutionalRelevance * WEIGHT_INSTITUTIONAL).toFixed(2)} |
| **COMPOSITE SCORE** | — | — | **${score.composite.toFixed(2)} / 10** |
**Decision:** ${decisionEmoji} **${decisionLabel}**
`;
}
/**
* Generate a batch scoring markdown table.
*
* Produces the Section 2 batch table from the template format.
* Scores must be in the same order as inputs (one score per input).
*
* @param inputs - Scoring inputs with titles and references
* @param scores - Pre-computed significance scores (same order as inputs)
* @returns Markdown table string
*/
export function formatBatchMarkdown(
inputs: readonly SignificanceScoringInput[],
scores: readonly SignificanceScore[]
): string {
const header =
'| Event | EP Reference | Parl. | Policy | Public | Urgency | Instit. | **Composite** | Decision |';
const separator =
'|-------|-------------|:-----:|:------:|:------:|:-------:|:-------:|:-------------:|----------|';
if (inputs.length !== scores.length) {
throw new Error(
`formatBatchMarkdown: inputs.length (${inputs.length}) !== scores.length (${scores.length}). Arrays must be aligned.`
);
}
const rows = inputs.map((input, i) => {
const s = scores[i] as SignificanceScore;
const decisionLabel =
s.decision === 'publish' ? 'Publish' : s.decision === 'hold' ? 'Hold' : 'Skip';
const safeTitle = sanitizeMdCell(input.title);
const safeRef = normalizeRef(input.reference);
return `| ${safeTitle} | ${safeRef ? sanitizeMdCell(safeRef) : '—'} | ${s.parliamentarySignificance.toFixed(1)} | ${s.policyImpact.toFixed(1)} | ${s.publicInterest.toFixed(1)} | ${s.temporalUrgency.toFixed(1)} | ${s.institutionalRelevance.toFixed(1)} | **${s.composite.toFixed(2)}** | ${decisionLabel} |`;
});
return [header, separator, ...rows].join('\n');
}
|