How your feed picks the next post: the code

These are the files that do most of the work. The comments explain why each part works the way it does. If anything is unclear, or you would do it differently, tell me. I will also send you the full code for free, with nothing to sign up for. Ask for the full code

src/core/recommender.ts

The feed itself. It gathers candidates, scores each one in parts you can read, applies the test slots and the run rule, and learns from each post. 181 lines

import { PARAMS } from "./params.ts";
import { type Post, SIMILAR, type Topic, TOPICS } from "./topics.ts";

export type Source = "yours" | "similar" | "popular" | "fresh";
export const SOURCES: Source[] = ["yours", "similar", "popular", "fresh"];

export interface Settings {
  diversity: boolean;
  exploration: boolean;
}
export const DEFAULT_SETTINGS: Settings = { diversity: true, exploration: true };

export interface Reaction {
  dwellSeconds: number;
  liked: boolean;
  notInterested: boolean;
}

const perTopic = <T>(v: () => T) => Object.fromEntries(TOPICS.map((t) => [t, v()])) as Record<Topic, T>;

export class Profile {
  affinity = perTopic<number | null>(() => null);
  shown = perTopic(() => 0);
  seconds = perTopic(() => 0);
  likes = perTopic(() => 0);
  fatigue = perTopic(() => 0);
  history: Post[] = [];
  seen = new Set<number>();

  match(t: Topic): number {
    return this.affinity[t] ?? PARAMS.learning.prior;
  }

  tested(t: Topic): boolean {
    return this.affinity[t] !== null;
  }
}

export interface Learned {
  topic: Topic;
  signal: number;
  before: number;
  after: number;
  skipped: boolean;
  watched: number;
}

// One number per post: how much of it the visitor watched, plus a like, minus a skip or a "not interested".
export function signalOf(r: Reaction): { signal: number; skipped: boolean; watched: number } {
  const L = PARAMS.learning;
  const watched = Math.min(r.dwellSeconds / L.fullWatchSeconds, 1);
  const skipped = r.dwellSeconds < L.quickSkipSeconds;
  let signal = L.dwellWeight * watched;
  if (r.liked) signal += L.likeWeight;
  if (skipped) signal -= L.skipPenalty;
  if (r.notInterested) signal -= L.notInterestedPenalty;
  return { signal, skipped, watched };
}

export function shownPost(p: Profile, post: Post): void {
  p.history.push(post);
  p.seen.add(post.id);
  p.shown[post.topic]++;
  for (const t of TOPICS) if (p.fatigue[t] > 0) p.fatigue[t]--;
}

export function learn(p: Profile, post: Post, r: Reaction): Learned {
  const { signal, skipped, watched } = signalOf(r);
  const before = p.match(post.topic);
  const after = before + PARAMS.learning.rate * (signal - before);
  p.affinity[post.topic] = after;
  p.seconds[post.topic] += r.dwellSeconds;
  if (r.liked) p.likes[post.topic]++;
  if (r.notInterested) p.fatigue[post.topic] = PARAMS.scoring.fatiguePosts;
  return { topic: post.topic, signal, before, after, skipped, watched };
}

export function search(p: Profile, t: Topic): void {
  p.affinity[t] = Math.max(p.match(t), PARAMS.learning.searchLift);
  p.fatigue[t] = 0;
}

export interface Candidate {
  post: Post;
  sources: Source[];
}

const byTopicMatch = (p: Profile) => [...TOPICS].sort((a, b) => p.match(b) - p.match(a) || TOPICS.indexOf(a) - TOPICS.indexOf(b));

export function gather(p: Profile, posts: Post[]): Candidate[] {
  const C = PARAMS.candidates;
  const unseen = posts.filter((x) => !p.seen.has(x.id));
  const found = new Map<number, Candidate>();
  const add = (list: Post[], source: Source) => {
    for (const post of list) {
      const c = found.get(post.id);
      if (c) {
        if (!c.sources.includes(source)) c.sources.push(source);
      } else found.set(post.id, { post, sources: [source] });
    }
  };
  // Only topics the visitor has actually reacted to count as theirs.
  const yours = byTopicMatch(p).filter((t) => p.tested(t)).slice(0, C.yourTopics);
  add(unseen.filter((x) => yours.includes(x.topic)), "yours");
  const similar = new Set(yours.slice(0, C.similarFrom).flatMap((t) => SIMILAR[t]).filter((t) => !yours.includes(t)));
  add(unseen.filter((x) => similar.has(x.topic)), "similar");
  add([...unseen].sort((a, b) => b.popularity - a.popularity || a.id - b.id).slice(0, C.popular), "popular");
  add([...unseen].sort((a, b) => a.ageHours - b.ageHours || a.id - b.id).slice(0, C.fresh), "fresh");
  return [...found.values()];
}

export interface Parts {
  match: number;
  popular: number;
  fresh: number;
  recent: number;
  fatigue: number;
}
export interface Scored extends Candidate {
  parts: Parts;
  total: number;
}

export function freshness(ageHours: number): number {
  return Math.pow(0.5, ageHours / PARAMS.scoring.freshHalfLifeHours);
}

export function score(p: Profile, c: Candidate): Scored {
  const S = PARAMS.scoring;
  const t = c.post.topic;
  const recentCount = p.history.slice(-S.recentWindow).filter((x) => x.topic === t).length;
  const parts: Parts = {
    match: S.match * p.match(t),
    popular: S.popular * c.post.popularity,
    fresh: S.fresh * freshness(c.post.ageHours),
    recent: -S.recentPenalty * recentCount,
    fatigue: -S.fatiguePenalty * (p.fatigue[t] / S.fatiguePosts),
  };
  const total = parts.match + parts.popular + parts.fresh + parts.recent + parts.fatigue;
  return { ...c, parts, total };
}

export type Reason = "best" | "explore" | "diversity";

export interface Decision {
  gathered: number;
  bySource: Record<Source, number>;
  ranked: Scored[];
  picked: Scored;
  reason: Reason;
  passedOver: Scored | null;
  blockedTopic: Topic | null;
}

export function runTopic(p: Profile): Topic | null {
  const n = PARAMS.diversity.maxInRow;
  const last = p.history.slice(-n);
  return last.length === n && last.every((x) => x.topic === last[0].topic) ? last[0].topic : null;
}

export function decide(p: Profile, posts: Post[], settings: Settings, rng: () => number): Decision | null {
  const candidates = gather(p, posts);
  if (candidates.length === 0) return null;
  const bySource = Object.fromEntries(SOURCES.map((s) => [s, 0])) as Record<Source, number>;
  for (const c of candidates) for (const s of c.sources) bySource[s]++;
  const ranked = candidates.map((c) => score(p, c)).sort((a, b) => b.total - a.total || a.post.id - b.post.id);

  const blockedTopic = settings.diversity ? runTopic(p) : null;
  const allowed = blockedTopic ? ranked.filter((c) => c.post.topic !== blockedTopic) : ranked;
  const pool = allowed.length ? allowed : ranked;
  // Drawn every step, rule on or off, so switching exploration off leaves the rest of the run's randomness unchanged.
  const roll = rng();
  if (settings.exploration && roll < PARAMS.exploration.share) {
    const least = Math.min(...pool.map((c) => p.shown[c.post.topic]));
    const picked = pool.find((c) => p.shown[c.post.topic] === least)!;
    return { gathered: candidates.length, bySource, ranked, picked, reason: "explore", passedOver: null, blockedTopic };
  }
  const picked = pool[0];
  const passedOver = picked === ranked[0] ? null : ranked[0];
  return { gathered: candidates.length, bySource, ranked, picked, reason: passedOver ? "diversity" : "best", passedOver, blockedTopic };
}

src/core/user.ts

A simulated visitor with known tastes. It turns a taste into a watch time and a chance of a like. 25 lines

import { PARAMS } from "./params.ts";
import type { Reaction } from "./recommender.ts";
import { normal } from "./rng.ts";
import type { Post, Topic } from "./topics.ts";

// A simulated visitor with known tastes. watch is 0 to 1 per topic; like overrides the chance of a like.
export interface Taste {
  watch: Partial<Record<Topic, number>>;
  otherwise: number;
  like?: Partial<Record<Topic, number>>;
}

export type Habit = "watch" | "skip" | "notInterested";

export function react(taste: Taste, post: Post, rng: () => number, habit: Habit = "watch"): Reaction {
  const U = PARAMS.user;
  const w = taste.watch[post.topic] ?? taste.otherwise;
  const z = normal(rng);
  const likeRoll = rng();
  if (habit === "skip") return { dwellSeconds: U.fastSkipSeconds, liked: false, notInterested: false };
  if (habit === "notInterested") return { dwellSeconds: U.fastSkipSeconds, liked: false, notInterested: true };
  const dwellSeconds = Math.min(U.maxWatchSeconds, Math.max(U.minWatchSeconds, U.watchScaleSeconds * w * Math.exp(U.watchNoise * z)));
  const likeChance = taste.like?.[post.topic] ?? U.likeRate * w;
  return { dwellSeconds, liked: likeRoll < likeChance, notInterested: false };
}

src/core/sim.ts

Runs one visitor through the feed. The feed and the visitor draw from separate seeded streams, so a run repeats exactly. 41 lines

import { DEFAULT_SETTINGS, decide, type Decision, learn, Profile, search, type Settings, shownPost } from "./recommender.ts";
import { makeRng } from "./rng.ts";
import type { Post, Topic } from "./topics.ts";
import { type Habit, react, type Taste } from "./user.ts";

export interface Phase {
  posts: number;
  taste: Taste;
  // Habit for one topic during this phase, for the steering runs.
  habit?: { topic: Topic; habit: Habit };
  searchFor?: Topic;
}

export interface Run {
  topics: Topic[];
  decisions: Decision[];
  profile: Profile;
}

// The recommender and the simulated visitor draw from separate streams, so a change in one leaves the other's draws alone.
export function simulate(posts: Post[], phases: Phase[], seed: number, settings: Settings = DEFAULT_SETTINGS): Run {
  const feedRng = makeRng(seed * 2 + 1);
  const userRng = makeRng(seed * 2 + 2);
  const profile = new Profile();
  const topics: Topic[] = [];
  const decisions: Decision[] = [];
  for (const phase of phases) {
    if (phase.searchFor) search(profile, phase.searchFor);
    for (let i = 0; i < phase.posts; i++) {
      const d = decide(profile, posts, settings, feedRng);
      if (!d) return { topics, decisions, profile };
      const post = d.picked.post;
      shownPost(profile, post);
      const habit = phase.habit && phase.habit.topic === post.topic ? phase.habit.habit : "watch";
      learn(profile, post, react(phase.taste, post, userRng, habit));
      topics.push(post.topic);
      decisions.push(d);
    }
  }
  return { topics, decisions, profile };
}