Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

refactor(priority): build every priority score from one shared core (#1754)

Cihan0450c4fce07c
diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.js
index cebdd01f0..c5d153020 100644
--- a/server/src/lib/action-center/priority.js
+++ b/server/src/lib/action-center/priority.js
@@ -26,11 +26,21 @@
*
* Pure: the caller reads the signals and the prompts' demand and passes them
* in. Alongside the score it returns the facts it rests on, from which the
- * app writes "Why this priority?" in the reader's language.
+ * app writes "Why this priority?" in the reader's language. Its scales, sum,
+ * past success and levels are the ones every screen's score shares
+ * (priority-core.js, learning D4).
*/
import { resolve } from '../../config/action-engine.js';
-import { INTENT_WEIGHTS } from '../opportunity-limits.js';
+import {
+ INTENT_WEIGHTS,
+ clamp,
+ levelOf,
+ logScale,
+ pastSuccessOf as pastSuccessAt,
+ round,
+ weightedScore,
+} from '../priority-core.js';
const DAY_MS = 86_400_000;
@@ -204,9 +214,6 @@ function realDemandOf(payloads, prompts) {
return { level, floor };
}
-const clamp01 = (n) => Math.min(1, Math.max(0, n));
-const round2 = (n) => Math.round(n * 100) / 100;
-
/** What kind of change a finding is; a kind this table has not met counts as a gap. */
function changeOf(kind) {
return KIND_CHANGE[kind] ?? 'gap';
@@ -214,7 +221,7 @@ function changeOf(kind) {
/** Demand on the shared log scale: 0 → 0, `demandFullAt` and above → 1. */
function demandScale(value) {
- return clamp01(Math.log10(1 + value) / Math.log10(1 + P.demandFullAt));
+ return logScale(value, P.demandFullAt);
}
/** The sum of the `demandTopTargets` largest values. */
@@ -345,7 +352,7 @@ function demandAndValue(payloads, signals, prompts) {
function confidenceOf(signals) {
const kinds = new Set(signals.map((s) => s.kind));
const sources = new Set(signals.flatMap((s) => (Array.isArray(s.source) ? s.source : [])));
- const value = clamp01(
+ const value = clamp(
0.3 + 0.2 * Math.max(kinds.size - 1, 0) + 0.2 * Math.max(sources.size - 1, 0),
);
return { value, kinds: kinds.size, sources: sources.size };
@@ -374,7 +381,7 @@ function sentByHand(action) {
return {
change: 'gap',
severity,
- confidence: clamp01(0.3 + 0.15 * gaps.length),
+ confidence: clamp(0.3 + 0.15 * gaps.length),
recoverability: 0.7,
subject: { entity: 'platforms', count: gaps.length },
};
@@ -440,6 +447,17 @@ function sentByHand(action) {
return null;
}
+/** The factors' weights, in the order they add up. */
+const WEIGHTS = {
+ impact: P.weightImpact,
+ demand: P.weightDemand,
+ severity: P.weightSeverity,
+ businessValue: P.weightBusinessValue,
+ confidence: P.weightConfidence,
+ recoverability: P.weightRecoverability,
+ recency: P.weightRecency,
+};
+
/**
* Past success (learning B4): from a kind's results at this brand, the
* share that improved, shrunk toward the prior by a few imagined results,
@@ -448,20 +466,16 @@ function sentByHand(action) {
* @param {{ improved?: number, results?: number } | undefined} track
*/
export function pastSuccessOf(track) {
- const improved = Math.max(0, Math.floor(Number(track?.improved) || 0));
- const results = Math.max(improved, Math.floor(Number(track?.results) || 0));
- const rate =
- (improved + P.pastSuccessPseudoCount * P.pastSuccessPrior) /
- (results + P.pastSuccessPseudoCount);
- return { rate, points: (rate - P.pastSuccessPrior) * P.pastSuccessSwing, improved, results };
+ return pastSuccessAt(track, {
+ prior: P.pastSuccessPrior,
+ pseudoCount: P.pastSuccessPseudoCount,
+ swing: P.pastSuccessSwing,
+ });
}
/** The level a score falls in. */
export function priorityLevel(score) {
- if (score >= P.levelCritical) return 'critical';
- if (score >= P.levelHigh) return 'high';
- if (score >= P.levelMedium) return 'medium';
- return 'low';
+ return levelOf(score, { critical: P.levelCritical, high: P.levelHigh, medium: P.levelMedium });
}
/**
@@ -538,16 +552,7 @@ export function scorePriority(
recency,
};
const past = pastSuccessOf(track.get(action.kind));
- const score = Math.round(
- factors.impact * P.weightImpact +
- factors.demand * P.weightDemand +
- factors.severity * P.weightSeverity +
- factors.businessValue * P.weightBusinessValue +
- factors.confidence * P.weightConfidence +
- factors.recoverability * P.weightRecoverability +
- factors.recency * P.weightRecency +
- past.points,
- );
+ const score = Math.round(weightedScore(factors, WEIGHTS).total + past.points);
const bounded = Math.min(100, Math.max(0, score));
const p = action.payload ?? {};
@@ -577,13 +582,13 @@ export function scorePriority(
sources: confidence.sources,
// How its kind did here before (learning B4); null with nothing to go on.
pastSuccess: past.results
- ? { improved: past.improved, results: past.results, points: round2(past.points) }
+ ? { improved: past.improved, results: past.results, points: round(past.points) }
: null,
// Its rate only with a result behind it: with none, the prior would
// read as a measured 0.5.
factors: Object.fromEntries(
Object.entries({ ...factors, ...(past.results ? { pastSuccess: past.rate } : {}) }).map(
- ([k, v]) => [k, round2(v)],
+ ([k, v]) => [k, round(v)],
),
),
},
diff --git a/server/src/lib/audit/priority.js b/server/src/lib/audit/priority.js
index c0ddd7ecf..c3dd52976 100644
--- a/server/src/lib/audit/priority.js
+++ b/server/src/lib/audit/priority.js
@@ -14,8 +14,13 @@
* - Ease: how close the page is to passing. Its last score; unknown when
* never audited. A page whose template shares its gaps (SA-007) is easier:
* one fix covers every page of it.
+ *
+ * Its own composition (a product, not a weighted sum: a page worth nothing
+ * or with nothing to win isn't worth an audit, however easy); the pieces it
+ * shares with every screen's score are in priority-core.js (learning D4).
*/
+import { clamp, round } from '../priority-core.js';
import { templateOf } from './templates.js';
export const PRIORITY_WEIGHTS = Object.freeze({
@@ -53,9 +58,6 @@ export const PRIORITY_WEIGHTS = Object.freeze({
}),
});
-const clamp = (n, min, max) => Math.min(max, Math.max(min, n));
-const round2 = (n) => Math.round(n * 100) / 100;
-
/**
* Each page's sessions as a share of the site's pages it beats (0–1), from
* the site's 30-day sessions. As GA's value percentile (scorePages), ties
@@ -129,9 +131,9 @@ export function scorePriority(row, rankSessions, sharedTemplates = new Set()) {
return {
priority: Math.round(100 * Math.cbrt(value * opportunity * ease)),
- value: round2(value),
- opportunity: round2(opportunity),
- ease: round2(ease),
+ value: round(value),
+ opportunity: round(opportunity),
+ ease: round(ease),
};
}
@@ -160,9 +162,9 @@ export function scoreTemplate(row, rankSessions) {
const ease = Math.min(1, w.ease.unaudited + w.ease.templateFix);
return {
priority: Math.round(100 * Math.cbrt(value * opportunity * ease)),
- value: round2(value),
- opportunity: round2(opportunity),
- ease: round2(ease),
+ value: round(value),
+ opportunity: round(opportunity),
+ ease: round(ease),
};
}
diff --git a/server/src/lib/opportunity-limits.js b/server/src/lib/opportunity-limits.js
index c69c8fff6..adff8cb70 100644
--- a/server/src/lib/opportunity-limits.js
+++ b/server/src/lib/opportunity-limits.js
@@ -4,9 +4,13 @@
* Opportunities are generated per prompt cluster: a group of prompts in one
* topic that a single piece of content can answer (lib/prompt-clusters.js).
* A cluster's figures are built from its member prompts, and the score keeps
- * its components so the detail page can say why it is what it is.
+ * its components so the detail page can say why it is what it is. Its scale
+ * and sum are the ones every screen's score shares (priority-core.js,
+ * learning D4).
*/
+import { INTENT_WEIGHTS, logScale, round, weightedScore } from './priority-core.js';
+
/**
* Opportunities one generation run may produce. A short list that gets read
* beats a long one that gets scrolled past, and generation runs nightly, so
@@ -26,21 +30,10 @@ export const OPPORTUNITY_WINDOW_DAYS = 30;
*/
const DEMAND_CEILING = 1_000_000;
-export const INTENT_WEIGHTS = {
- comparison: 1.0,
- 'best-top': 0.95,
- 'vs-review': 0.9,
- recommendation: 0.85,
- 'how-to': 0.75,
- 'problem-solving': 0.7,
- 'what-is': 0.6,
- other: 0.5,
-};
-
/** Score weights per component, out of 100. */
export const SCORE_WEIGHTS = { demand: 40, visibilityGap: 30, competitorGap: 20, intent: 10 };
-const round1 = (n) => Math.round(n * 10) / 10;
+const round1 = (n) => round(n, 1);
function mostFrequent(values, limit) {
const counts = new Map();
@@ -101,7 +94,7 @@ export function clusterMetrics(promptIds, prompts) {
/** Each score component on a 0–100 scale. */
export function scoreComponents({ demand, visibility, competitorGap, intent }) {
return {
- demand: round1(Math.min(Math.log10(1 + demand) / Math.log10(1 + DEMAND_CEILING), 1) * 100),
+ demand: round1(logScale(demand, DEMAND_CEILING) * 100),
visibilityGap: round1(100 - visibility),
competitorGap: round1(Math.min(Math.max(competitorGap, 0), 100)),
intent: round1((INTENT_WEIGHTS[intent] || INTENT_WEIGHTS.other) * 100),
@@ -110,11 +103,7 @@ export function scoreComponents({ demand, visibility, competitorGap, intent }) {
/** The weighted total of the components, 0–100. */
export function opportunityScore(components) {
- const total = Object.entries(SCORE_WEIGHTS).reduce(
- (s, [key, weight]) => s + (components[key] * weight) / 100,
- 0,
- );
- return Math.round(total * 100) / 100;
+ return round(weightedScore(components, SCORE_WEIGHTS, 100).total);
}
/**
diff --git a/server/src/lib/priority-core.fixtures.json b/server/src/lib/priority-core.fixtures.json
new file mode 100644
index 000000000..c5bcd3835
--- /dev/null
+++ b/server/src/lib/priority-core.fixtures.json
@@ -0,0 +1,479 @@
+{
+ "_note": "Cases checked against server/src/lib/priority-core.js and its web twin, web/src/lib/priority-core.ts (learning D4). Regenerate from the server file when a piece changes on purpose.",
+ "logScale": [
+ {
+ "value": 0,
+ "fullAt": 10000,
+ "result": 0
+ },
+ {
+ "value": 1,
+ "fullAt": 10000,
+ "result": 0.07525668186780549
+ },
+ {
+ "value": 10,
+ "fullAt": 10000,
+ "result": 0.26034534476721444
+ },
+ {
+ "value": 100,
+ "fullAt": 10000,
+ "result": 0.5010749033660213
+ },
+ {
+ "value": 1000,
+ "fullAt": 10000,
+ "result": 0.7501003756656575
+ },
+ {
+ "value": 10000,
+ "fullAt": 10000,
+ "result": 1
+ },
+ {
+ "value": 250000,
+ "fullAt": 10000,
+ "result": 1
+ },
+ {
+ "value": -5,
+ "fullAt": 10000,
+ "result": 0
+ },
+ {
+ "value": 37,
+ "fullAt": 1000,
+ "result": 0.5265183489530272
+ },
+ {
+ "value": 1000,
+ "fullAt": 1000,
+ "result": 1
+ },
+ {
+ "value": 3,
+ "fullAt": 20,
+ "result": 0.455340497393906
+ },
+ {
+ "value": 20,
+ "fullAt": 20,
+ "result": 1
+ },
+ {
+ "value": 45000,
+ "fullAt": 1000000,
+ "result": 0.7755369713075567
+ }
+ ],
+ "round": [
+ {
+ "n": 0.125,
+ "digits": 2,
+ "result": 0.13
+ },
+ {
+ "n": 0.135,
+ "digits": 2,
+ "result": 0.14
+ },
+ {
+ "n": 12.345,
+ "digits": 1,
+ "result": 12.3
+ },
+ {
+ "n": 0.6666666666666666,
+ "digits": 2,
+ "result": 0.67
+ },
+ {
+ "n": 99.95,
+ "digits": 1,
+ "result": 100
+ },
+ {
+ "n": -1.005,
+ "digits": 2,
+ "result": -1
+ }
+ ],
+ "weightedScore": [
+ {
+ "factors": {
+ "impact": 1,
+ "demand": 0.4,
+ "severity": 0.85,
+ "businessValue": 0.5,
+ "confidence": 0.3,
+ "recoverability": 1,
+ "recency": 0.93
+ },
+ "weights": {
+ "impact": 20,
+ "demand": 20,
+ "severity": 20,
+ "businessValue": 15,
+ "confidence": 10,
+ "recoverability": 10,
+ "recency": 5
+ },
+ "scale": 1,
+ "result": {
+ "total": 70.15,
+ "parts": [
+ {
+ "key": "impact",
+ "value": 1,
+ "weight": 20,
+ "points": 20
+ },
+ {
+ "key": "demand",
+ "value": 0.4,
+ "weight": 20,
+ "points": 8
+ },
+ {
+ "key": "severity",
+ "value": 0.85,
+ "weight": 20,
+ "points": 17
+ },
+ {
+ "key": "businessValue",
+ "value": 0.5,
+ "weight": 15,
+ "points": 7.5
+ },
+ {
+ "key": "confidence",
+ "value": 0.3,
+ "weight": 10,
+ "points": 3
+ },
+ {
+ "key": "recoverability",
+ "value": 1,
+ "weight": 10,
+ "points": 10
+ },
+ {
+ "key": "recency",
+ "value": 0.93,
+ "weight": 5,
+ "points": 4.65
+ }
+ ]
+ }
+ },
+ {
+ "factors": {
+ "demand": 66.7,
+ "visibilityGap": 87.3,
+ "competitorGap": 41.9,
+ "intent": 95
+ },
+ "weights": {
+ "demand": 40,
+ "visibilityGap": 30,
+ "competitorGap": 20,
+ "intent": 10
+ },
+ "scale": 100,
+ "result": {
+ "total": 70.75,
+ "parts": [
+ {
+ "key": "demand",
+ "value": 66.7,
+ "weight": 40,
+ "points": 26.68
+ },
+ {
+ "key": "visibilityGap",
+ "value": 87.3,
+ "weight": 30,
+ "points": 26.19
+ },
+ {
+ "key": "competitorGap",
+ "value": 41.9,
+ "weight": 20,
+ "points": 8.38
+ },
+ {
+ "key": "intent",
+ "value": 95,
+ "weight": 10,
+ "points": 9.5
+ }
+ ]
+ }
+ },
+ {
+ "factors": {
+ "severity": 0.6,
+ "opportunity": 0.82,
+ "pageValue": 0.5,
+ "citations": 0.37
+ },
+ "weights": {
+ "severity": 40,
+ "opportunity": 30,
+ "pageValue": 20,
+ "citations": 10
+ },
+ "scale": 1,
+ "result": {
+ "total": 62.3,
+ "parts": [
+ {
+ "key": "severity",
+ "value": 0.6,
+ "weight": 40,
+ "points": 24
+ },
+ {
+ "key": "opportunity",
+ "value": 0.82,
+ "weight": 30,
+ "points": 24.599999999999998
+ },
+ {
+ "key": "pageValue",
+ "value": 0.5,
+ "weight": 20,
+ "points": 10
+ },
+ {
+ "key": "citations",
+ "value": 0.37,
+ "weight": 10,
+ "points": 3.7
+ }
+ ]
+ }
+ }
+ ],
+ "pastSuccessOf": [
+ {
+ "track": null,
+ "settings": {
+ "prior": 0.5,
+ "pseudoCount": 5,
+ "swing": 20
+ },
+ "result": {
+ "rate": 0.5,
+ "points": 0,
+ "improved": 0,
+ "results": 0
+ }
+ },
+ {
+ "track": {
+ "improved": 0,
+ "results": 0
+ },
+ "settings": {
+ "prior": 0.5,
+ "pseudoCount": 5,
+ "swing": 20
+ },
+ "result": {
+ "rate": 0.5,
+ "points": 0,
+ "improved": 0,
+ "results": 0
+ }
+ },
+ {
+ "track": {
+ "improved": 3,
+ "results": 4
+ },
+ "settings": {
+ "prior": 0.5,
+ "pseudoCount": 5,
+ "swing": 20
+ },
+ "result": {
+ "rate": 0.6111111111111112,
+ "points": 2.222222222222223,
+ "improved": 3,
+ "results": 4
+ }
+ },
+ {
+ "track": {
+ "improved": 10,
+ "results": 10
+ },
+ "settings": {
+ "prior": 0.5,
+ "pseudoCount": 5,
+ "swing": 20
+ },
+ "result": {
+ "rate": 0.8333333333333334,
+ "points": 6.666666666666668,
+ "improved": 10,
+ "results": 10
+ }
+ },
+ {
+ "track": {
+ "improved": 0,
+ "results": 12
+ },
+ "settings": {
+ "prior": 0.5,
+ "pseudoCount": 5,
+ "swing": 20
+ },
+ "result": {
+ "rate": 0.14705882352941177,
+ "points": -7.0588235294117645,
+ "improved": 0,
+ "results": 12
+ }
+ },
+ {
+ "track": {
+ "improved": 7,
+ "results": 3
+ },
+ "settings": {
+ "prior": 0.5,
+ "pseudoCount": 5,
+ "swing": 20
+ },
+ "result": {
+ "rate": 0.7916666666666666,
+ "points": 5.833333333333332,
+ "improved": 7,
+ "results": 7
+ }
+ },
+ {
+ "track": {
+ "improved": "2",
+ "results": "9"
+ },
+ "settings": {
+ "prior": 0.5,
+ "pseudoCount": 5,
+ "swing": 20
+ },
+ "result": {
+ "rate": 0.32142857142857145,
+ "points": -3.571428571428571,
+ "improved": 2,
+ "results": 9
+ }
+ }
+ ],
+ "levelOf": [
+ {
+ "score": 100,
+ "cutoffs": {
+ "critical": 90,
+ "high": 75,
+ "medium": 50
+ },
+ "result": "critical"
+ },
+ {
+ "score": 90,
+ "cutoffs": {
+ "critical": 90,
+ "high": 75,
+ "medium": 50
+ },
+ "result": "critical"
+ },
+ {
+ "score": 89.9,
+ "cutoffs": {
+ "critical": 90,
+ "high": 75,
+ "medium": 50
+ },
+ "result": "high"
+ },
+ {
+ "score": 75,
+ "cutoffs": {
+ "critical": 90,
+ "high": 75,
+ "medium": 50
+ },
+ "result": "high"
+ },
+ {
+ "score": 50,
+ "cutoffs": {
+ "critical": 90,
+ "high": 75,
+ "medium": 50
+ },
+ "result": "medium"
+ },
+ {
+ "score": 49,
+ "cutoffs": {
+ "critical": 90,
+ "high": 75,
+ "medium": 50
+ },
+ "result": "low"
+ },
+ {
+ "score": 75,
+ "cutoffs": {
+ "critical": 75,
+ "high": 55,
+ "medium": 40
+ },
+ "result": "critical"
+ },
+ {
+ "score": 74.9,
+ "cutoffs": {
+ "critical": 75,
+ "high": 55,
+ "medium": 40
+ },
+ "result": "high"
+ },
+ {
+ "score": 55,
+ "cutoffs": {
+ "critical": 75,
+ "high": 55,
+ "medium": 40
+ },
+ "result": "high"
+ },
+ {
+ "score": 40,
+ "cutoffs": {
+ "critical": 75,
+ "high": 55,
+ "medium": 40
+ },
+ "result": "medium"
+ },
+ {
+ "score": 39.9,
+ "cutoffs": {
+ "critical": 75,
+ "high": 55,
+ "medium": 40
+ },
+ "result": "low"
+ }
+ ]
+}
diff --git a/server/src/lib/priority-core.js b/server/src/lib/priority-core.js
new file mode 100644
index 000000000..fd264566e
--- /dev/null
+++ b/server/src/lib/priority-core.js
@@ -0,0 +1,102 @@
+/**
+ * What every priority score is built from (learning D4).
+ *
+ * Four screens order work by a score: the Action Center
+ * (action-center/priority.js), content opportunities (opportunity-limits.js),
+ * the Site Audit inbox (audit/priority.js) and, in the web app, the Content
+ * Plan (web/src/lib/content/plan.ts, through this file's twin,
+ * web/src/lib/priority-core.ts). Each keeps its own factors: what makes an
+ * action urgent isn't what makes a page worth auditing. What they share is
+ * here, once: how a count becomes 0–1, the weight of a search's intent, how
+ * factors add up to a score, how a kind's past results move it, and how a
+ * score reads as a level. A change to one of these (a new kind of learning)
+ * reaches every screen that uses it.
+ *
+ * The cases in priority-core.fixtures.json are checked against this file and
+ * its web twin, so the two can't drift apart.
+ *
+ * Pure.
+ */
+
+/** `n` held between `min` and `max` (0 and 1 unless said). */
+export const clamp = (n, min = 0, max = 1) => Math.min(max, Math.max(min, n));
+
+/** `n` to `digits` decimals. */
+export function round(n, digits = 2) {
+ const f = 10 ** digits;
+ return Math.round(n * f) / f;
+}
+
+/**
+ * A count on a log scale: 0 → 0, `fullAt` and above → 1. Demand, sessions
+ * and conversions all grow by orders of magnitude, and on a straight scale
+ * the few largest would flatten the rest to 0.
+ */
+export function logScale(value, fullAt) {
+ return clamp(Math.log10(1 + Math.max(0, value)) / Math.log10(1 + fullAt));
+}
+
+/** How commercial a search is, by its intent: comparing and choosing above learning. */
+export const INTENT_WEIGHTS = Object.freeze({
+ comparison: 1.0,
+ 'best-top': 0.95,
+ 'vs-review': 0.9,
+ recommendation: 0.85,
+ 'how-to': 0.75,
+ 'problem-solving': 0.7,
+ 'what-is': 0.6,
+ other: 0.5,
+});
+
+/**
+ * Factors times their weights, added up in the weights' order: the total and
+ * what each factor gave. A factor's points are `value × weight / scale`:
+ * scale 1 for factors read 0–1, 100 for ones read 0–100 against weights out
+ * of 100.
+ *
+ * @param {Record<string, number>} factors
+ * @param {Record<string, number>} weights
+ * @returns {{ total: number, parts: Array<{ key: string, value: number, weight: number, points: number }> }}
+ */
+export function weightedScore(factors, weights, scale = 1) {
+ const parts = Object.entries(weights).map(([key, weight]) => ({
+ key,
+ value: factors[key],
+ weight,
+ points: (factors[key] * weight) / scale,
+ }));
+ return { total: parts.reduce((sum, p) => sum + p.points, 0), parts };
+}
+
+/**
+ * Past success (learning B4): from a kind's results at this brand, the share
+ * that improved, pulled toward `prior` by `pseudoCount` imagined results so a
+ * couple of results barely move it, and the points that moves a score: the
+ * rate's distance from the prior times `swing`. None read: the prior, no
+ * points.
+ *
+ * @param {{ improved?: number, results?: number } | undefined} track
+ * @param {{ prior: number, pseudoCount: number, swing: number }} settings
+ */
+export function pastSuccessOf(track, { prior, pseudoCount, swing }) {
+ const improved = Math.max(0, Math.floor(Number(track?.improved) || 0));
+ const results = Math.max(improved, Math.floor(Number(track?.results) || 0));
+ const rate = (improved + pseudoCount * prior) / (results + pseudoCount);
+ return { rate, points: (rate - prior) * swing, improved, results };
+}
+
+/**
+ * The level a score falls in, at a screen's own cut-offs: the Action
+ * Center's and the Content Plan's differ, since their scores spread
+ * differently.
+ *
+ * @param {number} score
+ * @param {{ critical: number, high: number, medium: number }} cutoffs
+ * @returns {'critical' | 'high' | 'medium' | 'low'}
+ */
+export function levelOf(score, { critical, high, medium }) {
+ if (score >= critical) return 'critical';
+ if (score >= high) return 'high';
+ if (score >= medium) return 'medium';
+ return 'low';
+}
diff --git a/server/src/lib/priority-core.test.js b/server/src/lib/priority-core.test.js
new file mode 100644
index 000000000..f3e26cad3
--- /dev/null
+++ b/server/src/lib/priority-core.test.js
@@ -0,0 +1,106 @@
+import { readFileSync } from 'fs';
+import { join } from 'path';
+import { describe, expect, it } from 'vitest';
+import {
+ INTENT_WEIGHTS,
+ clamp,
+ levelOf,
+ logScale,
+ pastSuccessOf,
+ round,
+ weightedScore,
+} from './priority-core.js';
+
+/**
+ * What every priority score is built from (learning D4). The fixtures are the
+ * cases the web twin (web/src/lib/priority-core.ts) is checked against too.
+ */
+
+const fixtures = JSON.parse(readFileSync(join(__dirname, 'priority-core.fixtures.json'), 'utf8'));
+const PAST = { prior: 0.5, pseudoCount: 5, swing: 20 };
+
+describe('the shared cases', () => {
+ it('logScale', () => {
+ for (const c of fixtures.logScale) expect(logScale(c.value, c.fullAt)).toBe(c.result);
+ });
+ it('round', () => {
+ for (const c of fixtures.round) expect(round(c.n, c.digits)).toBe(c.result);
+ });
+ it('weightedScore', () => {
+ for (const c of fixtures.weightedScore) {
+ expect(weightedScore(c.factors, c.weights, c.scale)).toEqual(c.result);
+ }
+ });
+ it('pastSuccessOf', () => {
+ for (const c of fixtures.pastSuccessOf) {
+ expect(pastSuccessOf(c.track, c.settings)).toEqual(c.result);
+ }
+ });
+ it('levelOf', () => {
+ for (const c of fixtures.levelOf) expect(levelOf(c.score, c.cutoffs)).toBe(c.result);
+ });
+});
+
+describe('logScale', () => {
+ it('runs from 0 at nothing to 1 at the full count, on a log scale', () => {
+ expect(logScale(0, 10000)).toBe(0);
+ expect(logScale(10000, 10000)).toBe(1);
+ expect(logScale(1_000_000, 10000)).toBe(1);
+ expect(logScale(100, 10000)).toBeCloseTo(0.5, 2);
+ // A negative count is no count.
+ expect(logScale(-3, 10000)).toBe(0);
+ });
+});
+
+describe('weightedScore', () => {
+ it("adds each factor's points in the weights' order and says what each gave", () => {
+ const { total, parts } = weightedScore({ a: 0.5, b: 1, ignored: 1 }, { b: 30, a: 20 });
+ expect(total).toBe(40);
+ expect(parts).toEqual([
+ { key: 'b', value: 1, weight: 30, points: 30 },
+ { key: 'a', value: 0.5, weight: 20, points: 10 },
+ ]);
+ });
+ it('reads factors given out of 100 against weights out of 100', () => {
+ expect(weightedScore({ a: 50, b: 100 }, { a: 60, b: 40 }, 100).total).toBe(70);
+ });
+});
+
+describe('pastSuccessOf', () => {
+ it('sits at the prior and moves nothing without results', () => {
+ expect(pastSuccessOf(undefined, PAST)).toEqual({
+ rate: 0.5,
+ points: 0,
+ improved: 0,
+ results: 0,
+ });
+ });
+ it('moves with the results, pulled toward the prior', () => {
+ const good = pastSuccessOf({ improved: 10, results: 10 }, PAST);
+ expect(good.rate).toBeCloseTo(12.5 / 15);
+ expect(good.points).toBeCloseTo(6.67, 2);
+ expect(pastSuccessOf({ improved: 0, results: 10 }, PAST).points).toBeCloseTo(-6.67, 2);
+ // More improved than results reads as all of them improved.
+ expect(pastSuccessOf({ improved: 4, results: 2 }, PAST).results).toBe(4);
+ });
+});
+
+describe('levelOf and clamp', () => {
+ it("reads a score at a screen's own cut-offs", () => {
+ const cutoffs = { critical: 90, high: 75, medium: 50 };
+ expect([95, 90, 80, 50, 10].map((s) => levelOf(s, cutoffs))).toEqual([
+ 'critical',
+ 'critical',
+ 'high',
+ 'medium',
+ 'low',
+ ]);
+ });
+ it('holds a number between bounds, 0 and 1 unless said', () => {
+ expect([clamp(-1), clamp(0.4), clamp(3), clamp(3, 0.1, 2)]).toEqual([0, 0.4, 1, 2]);
+ });
+ it('weighs comparing above learning', () => {
+ expect(INTENT_WEIGHTS.comparison).toBeGreaterThan(INTENT_WEIGHTS['what-is']);
+ expect(Object.isFrozen(INTENT_WEIGHTS)).toBe(true);
+ });
+});